Search code examples
androidandroid-layoutmenuitem

changing menu item programmatically is not working in android


I have a menu item and I want to change its visibility programmatically. The menu is this

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
     <item
        android:id="@+id/pencil"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:visible="true"
        android:title="@string/for_pencil"/>

</menu>

then some where in my code I have

((MenuItem) findViewById(R.id. pencil)).setVisible(false);

Error:

E/AndroidRuntime(13845): FATAL EXCEPTION: main
E/AndroidRuntime(13845): java.lang.ClassCastException: com.android.internal.view.menu.ActionMenuItemView cannot be cast to android.view.MenuItem

Any help sorting this out?


Solution

  • Since you did not provide any other code, I can't say much about it.

    However, whenever you want to change the menu, you should call invalidateOptionsMenu(). What that does is it invalidates the menu, which in turn forces it to be recreated. During its recreation, one of the callbacks is onPrepareOptionsMenu(Menu menu). This is where you can make the change to your menu.

    Example:

    // This is where I want to change the menu. Can be anywhere in your activity.
    invalidateOptionsMenu();
    

    Then override this method

    // Override this method to do what you want when the menu is recreated
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.pencil).setVisible(false);
        return super.onPrepareOptionsMenu(menu);
    }