Android: Multiple Option Menus in one Activity


I have an Activity containing a ViewFlipper and would like to show a different option menu for each view in that ViewFlipper. That is, the type of menu displayed when the menu button is pressed would depend on the type of the current view.

However, onCreateOptionsMenu() is called only once (when showing the option menu for the first time), so creating the different menus can’t be implemented there.

How could I solve this?


First read about onPrepareOptionsMenu(Menu menu)

Each time the user presses the Menu on their Android device while inside one of your activities, the onPrepareOptionsMenu method is called. The first time the menu is shown (i.e. only once), the onCreateOptionsMenu method is called.

Basically, the onPrepareOptionsMenu method is where you should make any changes such as enabling/disabling certain menu items, or changing the menu item text depending on the circumstances.

So do this (Don’t use onCreateOptionsMenu(Menu menu) )

//Dynamically create context Menu
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear(); //Clear view of previous menu
        MenuInflater inflater = getMenuInflater();
            inflater.inflate(, menu);
            inflater.inflate(, menu);
        return super.onPrepareOptionsMenu(menu);

Answered By – Pankaj Kumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published