How to remove MenuItems from Menu programmatically?
android, java
Solution
Try just not show them using:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.menuItemToLeft).setVisible(true);
menu.findItem(R.id.menuItemToRight).setVisible(false);
return true;
}
//true or false depending on your requirements
or to delete:
menu.removeItem(x); //where x is the number of the menu item from 0,1,...
You may then need to create the MenuItem again using menu.Add()
Problem
I'm developing some Android application, and I've got some code for menu: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:showAsAction="ifRoom" android:id="@+id/menuItemToLeft" android:icon="@drawable/to_left" /> <item android:showAsAction="ifRoom" android:id="@+id/menuItemToRight" android:icon="@drawable/to_right"/> </menu> ``` I use "showAsAction" in order to show this items on Action Bar. Also I've got 3 tabs for navigation. But there is the following task: remove (or set visibility as false) this items from Action bar when tab with 0 positions is selected. But I don't understand how I can do it: ``` public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); if (tab.getPosition()==0) { //some code } } ```