androidandroid-4.0-ice-cream-sandwichoptions-menu

Can't click Options Menu if initial menu size is zero


Lets assume, that I have two activities. One called MainActivity, and the other called PopupActivity. I want to have a context menu in MainActivity, after the user visited PopupActivity.

    Main [no menu] --> startActivity() / startActivityForResult() 
    ==> Popup --> back / finish() 
    ==> Main [now has menu].

Environment details:

If the MainActivity has at least one element at the begining state, i can add / remove the desired menu items via onPrepareOptionsMenu. But if the MainActiviy has 0 menu elements inside, android doesn't even render the menu button on the top right corner.

My question is:

Workaround soultions can't work (like separating the Activity into two, etc.), because the whole problem is a bit more complex, but the core of it is this. I don't need menu items at the begining state, and i need them in a second one.

main_menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android">    
    <item android:id="@+id/menu_add" android:title="@string/add"></item>            
    <item android:id="@+id/menu_remove" android:title="@string/remove" ></item>
</menu>

MainActivity.java

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

@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
    if (initState)
    {
        menu.findItem(R.id.menu_add).setVisible(false);
        menu.findItem(R.id.menu_remove).setVisible(false);
    } else
    {
        menu.findItem(R.id.menu_add).setVisible(true);
        menu.findItem(R.id.menu_remove).setVisible(true);
    }
    return super.onPrepareOptionsMenu(menu);
}

Solution

  • First Create two menu. one for initial stage and second for after visited PopupActivity.

    Replace Your onCreateOptionsMenu() with

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
    
       if (initState)
           inflater.inflate(R.menu.invisible_main_menu, menu);
       else
           inflater.inflate(R.menu.visible_main_menu, menu);
    
        return true;
    }