2

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?

rupesh
  • 2,865
  • 4
  • 24
  • 50
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87
  • If you add menu dinamically on your activity, you need to invalidate the menu. When it is re-created then you just do not add the item you want. If from a resource file, I assume that you load the Menu, and beffore adding it to the activity you could remove or hide the unwanted part. Override the onCreateOptionsMenu(Menu menu) There is the handle of the menu for the activity. – soynerdito Jul 05 '13 at 20:35

2 Answers2

32

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);
}
btse
  • 7,811
  • 3
  • 25
  • 30
0

The way to access the menu through the toolbar, and no need to dedicate variable:

MenuItem menuItem = ((Toolbar)findViewById(R.id.toolbar)).getMenu().findItem(R.id.pencil);
menuItem.setVisible(true);
IQ.feature
  • 600
  • 6
  • 16