Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 934
Amar Ilindra Avatar asked May 31 '16 10:05

Amar Ilindra


People also ask

How do I make my action bar invisible?

If you want to hide Action Bar from the entire application (from all Activities and fragments), then you can use this method. Just go to res -> values -> styles. xml and change the base application to “Theme. AppCompat.

How do you make a menu item invisible?

Call invalidateOptionsMenu() when you want to hide the option.

What is onCreateOptionsMenu in Android?

If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the app bar.


2 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 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.

like image 113
Chol Avatar answered Oct 19 '22 15:10

Chol


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

like image 39
Csabi Avatar answered Oct 19 '22 16:10

Csabi