How to show / hide an action menu item programmatically using Click Event

By default, I set the visibility to false using the 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 the user clicks a button in my activity.

+4
source share
3 answers

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 the method in which you want to show / hide the icon, just set the boolean hideIcon to true or false and call:

invalidateOptionsMenu();

to refresh the menu.

+5
source

get an instance of this menu item, and you can set its β€œVisibility” element each 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's response call invalidateOptionsMenu();

+1

While you can create a class field

   private Menu menu;

and write its value in onCreateOptionsMenu ()

   this.menu = menu;

Then write the code in clickListener

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

All Articles