2

I manage some Fragment's in my own ActionBarActivity named MainActivity. One Fragment is shown at one time. The example should be simple. The Fragment which is showing should have got an option menu under certain conditions.

Here my code:

public class MainActivity extends ActionBarActivity{

...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // The certain conditions. You might know the background. ;-)
        final boolean hasMenu = mNavigationDrawer.isDrawerOpen() ? false : true;

        // The reference to the fragment which is shown
        mCurrentShownFragment.setHasOptionsMenu(hasMenu);

        return super.onCreateOptionsMenu(menu);

    }

...

}

Because of the invocation of mCurrentShownFragment.setHasOptionMenu(true) MainActivity's and Fragment's onCreateOptionMenu(...) is called two times.

First question: Why?
Second question: Is that fine?
Third question: If second question's answer is false. How could I prevent this?

Best regards, Barock

Barock
  • 427
  • 1
  • 4
  • 12
  • Have you put a breakpoint on your `Fragment`'s `onCreateOptionMenu()` and see if both invocations came from the same point? Other than that, having it called seems fine to me. The only thing is that it happens twice. – shkschneider May 06 '15 at 08:21

1 Answers1

1

Take a look at the source of setHasOptionsMenu :

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

it calls the supportInvalidateOptionsMenu() :

public void supportInvalidateOptionsMenu() {
    if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
        // If we are running on HC or greater, we can use the framework
        // API to invalidate the options menu.
        ActivityCompatHoneycomb.invalidateOptionsMenu(this);
        return;
    }

    mOptionsMenuInvalidated = true;
}

Which calls invalidateOptionsMenu(this) :

public void invalidateOptionsMenu () Added in API level 11

Declare that the options menu has changed, so should be recreated. The onCreateOptionsMenu(Menu) method will be called the next time it needs to be displayed.

So it's absolutly normal that it calls the onCreateOptionsMenu cause that's how setHasOptionsMenu works

Strider
  • 4,452
  • 3
  • 24
  • 35