How to dynamically change menu in onCreateOptionsMenu

Balkyto picture Balkyto · Sep 24, 2012 · Viewed 7.3k times · Source

I have small problem and I'd like to solve it with dynamical menu:

public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    switch(Globals.editMode){
    case Globals.MODE_NONE:
        getSupportMenuInflater().inflate(R.menu.imagehandlingmain_menu, menu);
        break;
    case Globals.MODE_MOVE:
        getSupportMenuInflater().inflate(R.menu.savecancel_menu, menu);
        break;
    case Globals.MODE_ROTATE:
        getSupportMenuInflater().inflate(R.menu.savecancel_menu, menu);
        break;
    case Globals.MODE_SCALE:
        getSupportMenuInflater().inflate(R.menu.savecancel_menu, menu);
        break;
    }
    //getSupportMenuInflater().inflate(R.menu.imagehandlingmain_menu, menu);
    return true;

I have two menus, menu where you can select work mode, and while in certain work mode menu should change to "cancel" and "save".

So the idea is that you enter to one of modes, and then if you decide not to save your work you can cancel it and return to previous state.

Now, as I assumed onCreateOptionsMenu is called only once, so how could / should I "reload" the whole menu when needed?

Answer

futtetennista picture futtetennista · Sep 24, 2012

You can use Activity.invalidateOptionsMenu(). This - as the name suggests - will invalidate the current menu and consequently Activity.onPrepareOptionsMenu() will be called again.