Question

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:

  • minSDK: 10 (needed for backward compatibility)
  • targetSDK: 17
  • targetDevice: GalaxyTab 2.0

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:

  • What do i miss?
  • How to tell android, to render the menu button, because i want to add menu items to it.

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);
}
Était-ce utile?

La 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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top