2017-03-19 30 views
0

私の目標は、アクションバーのメニュー項目の1つを非表示にし、メニュー項目をクリックした後に別の項目を表示することです。私のアプリケーションでは、私はToolbarを使用しています。私はすでに他の多くの質問を探していて、私が必要とするものを見つけられませんでした。どんな助けもありがとう。私は以下のコードを試しましたが、これはクリック後にアプリケーションがクラッシュします。アンドロイドのアクションバーのメニュー項目を非表示にするには?

public boolean onOptionsItemSelected(MenuItem item) { 
    final SwipeRefreshLayout mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); 
    switch (item.getItemId()) { 
     case R.id.action_next: 
      //code 
      MenuItem secondItem = (MenuItem) findViewById(R.id.action_next); 
      secondItem.setVisible(false); 
      return true; 

     case R.id.action_previous: 
      //code 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 
+0

の可能性のある重複した[メニューで設定し、視認性をプログラムアンドロイド](http://stackoverflow.com/questions/9030268/set-visibility-in-menu-programatically-android) – 0X0nosugar

答えて

3

あなたが非表示にonCreateOptionsMenuに表示し、onOptionsItemSelected内1は、可視および他の不可視したいメニュー項目への参照を取得することができます:あなたは間違って上書きしている

private MenuItem itemToHide; 
private MenuItem itemToShow; 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    itemToHide = menu.findItem(R.id.item_to_hide); 
    itemToShow = menu.findItem(R.id.item_to_show); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.action_next: 
      // hide the menu item 
      itemToHide.setVisible(false); 
      // show the menu item 
      itemToShow.setVisible(true); 
      return true; 
    }  

    return super.onOptionsItemSelected(item); 
} 
+0

大変ありがとうございます。 – Maros1515

+0

問題が解決してうれしいです。 –

1

を関数。

使用この:

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 

    inflater.inflate(R.menu.menu, menu); 
    MenuItem item = menu.findItem(R.id.action_next); 
    item.setVisible(false); //hide it 
    super.onCreateOptionsMenu(menu, inflater); 
} 
+0

ありがとう、私はそれに気付かなかった。 – Maros1515

+0

あなたは歓迎です@ Maros1515 – rafsanahmad007

関連する問題