Calling setHasOptionsMenu(true) from a fragment results in multiple calls to onCreateOptionsMenu in Activity

18,566

It's absolutely "normal." It may not fit with your particular use case, but it's definitely intended behavior.

Take a look at the source for android.support.v4.app.Fragment.setHasOptionsMenu():

public void setHasOptionsMenu(boolean hasMenu) {
    if (mHasMenu != hasMenu) {
        mHasMenu = hasMenu;
        if (isAdded() && !isHidden()) {
            mActivity.supportInvalidateOptionsMenu();
        }
    }
}

You can see it calls supportInvalidateOptionsMenu() on it's activity, which ultimately leads to onCreateOptionsMenu() being called on the activity and all of it's fragments. It's how the framework manages updating the options menu when a fragment is added/removed from an activity's fragment manager.

Share:
18,566
facetoe
Author by

facetoe

I'm a guy trying to learn how to program.

Updated on June 14, 2022

Comments

  • facetoe
    facetoe almost 2 years

    I have a simple Activity that contains a ViewPager. I'm attempting to add some menu items to the menu from one of my Fragments, however I'm getting some strange behavior. Calling: setHasOptionsMenu(true); from my fragment results in the enclosing Activity's onCreateOptionsMenu() method to be called every time I change fragments in the ViewPager. Is this normal?