Jelly bean not calling onPrepareOptionsMenu() when opening the menu for the first time
Asked Answered
C

2

9

I'm overriding onPrepareOptionsMenu to hide and show menu items. When testing it with the API level 16 emulator; onPrepareOptionsMenu is not called when opening the menu for the first time. But when i reopen the menu it works. The problem is only with the first usage. You can simple test it with this;

@Override
public void onPrepareOptionsMenu(Menu menu) {
    Toast.makeText(this.getActivity(), "pre", Toast.LENGTH_SHORT).show();
    super.onPrepareOptionsMenu(menu);
}

Any ideas?

Capriccio answered 14/10, 2012 at 21:35 Comment(0)
N
17

onPrepareOptionsMenu() is called each time the user opens the menu on Gingerbread and below. From Honeycomb up the Options Menu is assumed to always be open when items are present in the ActionBar.

If you want to update the Options Menu during your activities lifecyle and within the onPrepareOptionsMenu() callback you need to call invalidateOptionsMenu() and the onPrepareOptionsMenu() will be called.

Could you not implement the code for your first usage in the onCreateOptionsMenu() callback? It is called every time the Options Menu is created and it is created on first use.

Needless answered 14/10, 2012 at 21:44 Comment(1)
Where do you call that from?Lavinialavinie
S
5

It is android bug: https://code.google.com/p/android/issues/detail?id=24231

When you first time press menu button, call invalidateOptionsMenu() or supportInvalidateOptionsMenu() if you use support library.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch(keyCode) {
    case KeyEvent.KEYCODE_MENU:
        if(mIsMenuFirstClick) {
            mIsMenuFirstClick = false;
            supportInvalidateOptionsMenu();
        }
    }
    return super.onKeyDown(keyCode, event);
}
Stanleigh answered 3/3, 2014 at 12:38 Comment(1)
Works beautifully, thanks! Note that in some cases it should be ActivityCompat.invalidateOptionsMenu(this);.Derril

© 2022 - 2024 — McMap. All rights reserved.