How to Show/Hide Action Bar item programmatically via Click Event

佐手、 提交于 2019-12-23 09:44:32

问题


By default I set the visibility to false by using following code.

@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;
    }

Now how can I make it visible again when user clicks a button in my activity.


回答1:


In your 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;
    }

In method where you want to show/hide the icon, just set the boolean hideIcon to true or false and call :

invalidateOptionsMenu();

to refresh the menu.




回答2:


get the instance of that menu item, and you can set its item Visibility every time.

        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);

and based on @chol answer call invalidateOptionsMenu();




回答3:


While you can create a class field

   private Menu menu;

and capture its value in onCreateOptionsMenu()

   this.menu = menu;

Then Write the code in clickListener

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


来源:https://stackoverflow.com/questions/37543244/how-to-show-hide-action-bar-item-programmatically-via-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!