문제

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