I have an action bar with a menuitem. How can I hide/show that menu item?
This is what I'm trying to do:
MenuItem item = (MenuItem) findViewById(R.id.addAction);
item.setVisible(false);
this.invalidateOptionsMenu();
I have an action bar with a menuitem. How can I hide/show that menu item?
This is what I'm trying to do:
MenuItem item = (MenuItem) findViewById(R.id.addAction);
item.setVisible(false);
this.invalidateOptionsMenu();
I was looking for an answer with a little more context. Now that I have figured it out, I will add that answer.
Hide button by default in menu xml
By default the share button will be hidden, as set by
android:visible="false"
.main_menu.xml
Show button in code
But the share button can optionally be shown based on some condition.
MainActivity.java
See also
If you did everything as in above answers, but a menu item is still visible, check that you reference to the unique resource. For instance, in onCreateOptionsMenu or onPrepareOptionsMenu
Ctrl+Click R.id.menu_open and check that it exists only in one menu file. In case when this resource is already used anywhere and loaded in an activity, it will try to hide there.
Initially set the menu item visibility to false in the menu layout file as follows :
You can then simply set the visibility of the menu item to false in your onCreateOptionsMenu() after inflating the menu.
According to Android Developer Official site,OnCreateOptionMenu(Menu menu) is not recomended for changing menu items or icons, visibility..etc at Runtime.
As Recomended You can use this onOptionsItemSelected(MenuItem item) method track user inputs.
If you need to change Menu Items at Run time, You can use onPrepareOptionsMenu(Menu menu) to change them
this code worked for me
You can use
toolbar.getMenu().clear();
to hide all the menu items at once