0

I've got an optionsmenu looking like this right now:

enter image description here

Lets say that if I click item 1, i want two new items added to the menu looking like this:

enter image description here

I'm having problems doing this at runtime(while it's open) since onCreateOptionsMenu is only called once and onPrepareOptionsMenu seems only to be called when the menubutton of the phone is clicked. I just want it to refresh with these new items added.

Thanks for any help!

Lucas Arrefelt
  • 3,879
  • 5
  • 41
  • 71
  • You want to update menu while it is open? Have you tried hiding and displaying it programmatically (without pressing menu button), so the onPrepareOptionsMenu would be called? – Sver May 02 '12 at 10:34
  • Yes, I've tried this approach using CloseOptionsMenu() and after OpenOptionsMenu(). This closes the menu, calls prepare but doesn't open it again.. – Lucas Arrefelt May 02 '12 at 10:41
  • 1
    Have you thought about using a sub-menu? (I know it won't add to the menu like you want, but the functionality is about what you seem to be looking for). – Barak May 02 '12 at 12:55
  • Yes i ended up using submenus. But it would have been neater having it my way, even though submenus offer the same functionality :) Since no answer has come yet, there some to be no simple solution. – Lucas Arrefelt May 02 '12 at 13:26

1 Answers1

0

When you select an option item it causes the system to close the options menu. This happens after onOptionsItemSelected() runs. I'm guessing what you need to have happen is for that entire process to complete then have the options menu programmatically opened again so onPrepareOptionsMenu() is called.

Try this:

  1. In onOptionsItemSelected(), when the user selects your "add two more options" option, set a flag in your activity but don't do anything else.

  2. Override onOptionsMenuClosed(). Check if the flag is set. If it is, then post to be executed by the UI thread on its next pass. It should do nothing but open the options menu again, e.g.

    runOnUiThread(new Runnable() { @Override public void run() { openOptionsMenu(); } });

  3. Override onPrepareOptionsMenu(). Check if the flag is set. If it is, then add your two additional menu items and un-set the flag. You'll need to do some additional work to prevent the "add more items" menu item from continuing to add new items every time its pressed, unless that's the behavior you're looking for.

jph
  • 2,181
  • 3
  • 30
  • 55