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