2016-05-31 40 views
4

默認情況下,我通過使用以下代碼將可見性設置爲false。如何通過Click事件以編程方式顯示/隱藏操作欄項目

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_items, menu); 
     menu.findItem(R.id.action_share).setVisible(false); 
     return true; 
    } 

現在,當用戶單擊我的活動中的某個按鈕時,如何再次使其可見。

回答

5

在你onCreateOptionsMenu:

public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_items, menu); 
     if (hideIcon){ 
      menu.findItem(R.id.action_share).setVisible(false); 
     }else{ 
      menu.findItem(R.id.action_share).setVisible(true); 
     } 
     return true; 
    } 

在方法要顯示/隱藏的圖標,只需設置布爾hideIcon爲真或假,並呼籲:

invalidateOptionsMenu(); 

刷新菜單。

+0

謝謝。工作 – Ramesh

1

獲取該菜單項的實例,並且每次都可以設置其項目可見性。

 Menu mMenu; 
     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.menu_items, menu); 
      mMenu = menu; 
      mMenu.findItem(R.id.action_share).setVisible(false); 
      return true; 
     } 

//somewhere else 

mMenu.findItem(R.id.action_share).setVisible(true); 

,並根據@chol應答呼叫invalidateOptionsMenu();

0

雖然你可以創建一個類字段

private Menu menu; 

和onCreateOptionsMenu捕獲其值()

this.menu = menu; 

然後寫clickListener中的代碼

this.menu.findItem(R.id.action_share).setVisible(true); 
+0

誰想出了類似的解決方案?嗯? – Csabi

相關問題