0

I have implemented ActionBar Navigation using Fragment. In my App i have one Activity and rest is in Fragments. In my MainActivity i am implementing menu like this.

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

Two Fragments uses Navigation Drawer and in their respected fragments i am inflating menu buttons to sort items.

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.sort_button_shops, menu);
    }

Now the Problem is if i open the Fragment 1 it works perfectly. When i open fragment 2, it shows 2 button to sort, one from Fragment 1 and the second one from Fragment 2.

I have tried to hide the button but it didn't worked. Any Help will be Appreciated. Thanks

user3789702
  • 201
  • 1
  • 3
  • 13
  • 1
    I make some MenuItems (the buttons I want to hide/show) in the declaration section of my Activity. I assign them in the onCreateOptionsMenu. Then, in code, I use `myItem.setVisible(true|false);`. Very simple. – Phantômaxx Jul 18 '14 at 15:16
  • I have already tried this, it is not working. I am surprised why the menu added in fragment 1 shown in fragment 2. As Every Fragment has its own menu. – user3789702 Jul 18 '14 at 15:26
  • I know this is a little old but see my answer. – tricknology Feb 20 '15 at 02:22

2 Answers2

1

When you inflate a new menu you are adding new items to the old Menu object, which is probably not what you intended.

Try this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.removeItem(R.id.your_menu_item);
    getMenuInflater().inflate(R.menu.main, menu);
return true;
}
tricknology
  • 1,092
  • 1
  • 15
  • 27
0

Try using this in onResume() of fragments.

MenuItem item = (MenuItem) findViewById(R.menu.activity_main);
item.setVisible(false);
this.invalidateOptionsMenu();
Bilal Haider
  • 83
  • 2
  • 6