malcoauri
malcoauri

Reputation: 12189

How to remove MenuItems from Menu programmatically?

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

Upvotes: 10

Views: 13115

Answers (2)

Kshitij Jhangra
Kshitij Jhangra

Reputation: 607

A very small solution for this :

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
Menu myMenu;


protected void onCreate(Bundle savedInstanceState) {
.....
}

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        myMenu = menu;
        return true;
    }

 @Override
    public boolean onNavigationItemSelected(MenuItem item) {

int id = item.getItemId();
if (id == R.id.feedsenglish)
        {
            myMenu.findItem(R.id.allfeeds).setVisible(false);
        }
}

Upvotes: 1

Stephen Walker
Stephen Walker

Reputation: 574

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

Upvotes: 28

Related Questions