Search code examples
androidandroid-actionbarsetcontentview

Variable to keep track of contentView, then call inalidateOptionsMenu()


My main goal is to refresh the options menu depending on what layout is current in the Activity. I don't want the buttons on my Action Bar when R.layout.preweb is active, but when setContentView is changed to R.layout.main becomes active, invalidateOptionsMenu and inflate. Here's what I have now:

private int mViewMode;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return mViewMode == 2;
}

And throughout my activity, in random methods, I have this:

setContentView(R.layout.preweb);
mViewMode = 1;

//or somewhere else

setContentView(R.layout.main);
mViewMode = 2;
invalidateOptionsMenu();

So basically, whenever mViewMode is set to 2, invalidateOptionsMenu is called and then onCreateOptionsMenu should retrigger, and being mViewMode now equals 2, I should then inflate. But nothing is happening - it never inflates.

What's up here? Any suggestions?


Solution

  • On invalidating menu using invalidateOptionsMenu(), method onPrepareOptionsMenu(android.view.Menu) will be called, not onCreateOptionsMenu(). So you need to override this method, and you need to write code to show menu item or hide menu item.

    For example

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (mViewMode == 2) {
            // Need to show menu items
            menu.findItem(R.id.menuitem1).setVisible(true);
            menu.findItem(R.id.menuitem2).setVisible(true);
        } else {
            // Need to hide menu items
            menu.findItem(R.id.menuitem1).setVisible(false);
            menu.findItem(R.id.menuitem2).setVisible(false);
        }      
        return true;
    }
    

    and onCreateOptionsMenu() does not gets called when you say invalidateOptionsMenu(), so no need to return false from there. You always need to return true from it.

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return true; 
    }