0

I have a settings menu item that is generated in MainActivity. All the MainActivity's job is to contain fragments that actually do the job. Those fragments have their own action bar items and they work as expected.

The settings menu item should show/hide, depending on a certain condition that is changing between fragments, so assuming the code is on MainActivity, it should be:

if (condition) menu.findItem(R.id.action_settings).setVisible(false);       
else menu.findItem(R.id.action_settings).setVisible(true);

Now I'm wondering where should I place the code because the condition changes between fragments but the actual menu item is on MainActivity.

2
  • can you post your code for better understanding!!
    – DjP
    Commented Jan 3, 2015 at 11:30
  • I didn't even know fragments could have menu items :O Anyway, you should implement listeners for the fragments which they can use to pass the information.
    – hypd09
    Commented Jan 3, 2015 at 11:30

2 Answers 2

0

Your condition might be OK and you can put it in your Activity's onPrepareOptionsMenu(). As you said this gets called just one time when you enter the Activity (with some exceptions).

You need to force the system to recall the Activity onPrepareOptionsMenu() when switching through fragments, and that is done - from anywhere - with the line invalidateOptionsMenu() (or, if necessary, getActivity().invalidateOptionsMenu()).

Good points to paste it might be Fragments onResume(), or any other point at which you think your condition state has changed.

Depending on your libraries, there's also a support method for API<11 called supportInvalidateOptionsMenu().

This should be called each time you want your Menu to change. However, if your fragments just add some items to a base, activity menu, take a look at this.

1
  • Apparently, onPrepareOptionsMenu() was enough to make it refresh as I expect it to be. I hope not to encounter any scenarios where this won't be enough
    – Amos
    Commented Jan 3, 2015 at 17:21
0

i think it is gonna work for you

public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.