dasmikko dasmikko - 14 days ago 7
Java Question

Can't hide actionbar menu item programatically

I'm trying to hide an Actionbar menu item if a shared preference is false.

I'm getting the shared preference as I want, but the menu item wont hide.

// Inflate a menu to be displayed in the toolbar
toolbar.inflateMenu(R.menu.activity_main_actionbar);

// Enable disable set start page item
if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
}


What am i doing wrong??

Answer

The right place for doing this is onPrepareOptionsMenu. From the docs,

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

So, I would recommend you to override onPrepareOptionsMenu and then check for the Shared Prefs inside it and show menu accordingly. Something like,

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // Enable disable set start page item
    if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
        toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
    }

    return true;
}