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

StackOverflow https://stackoverflow.com/questions/22151458

سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top