changing menu item programmatically is not working in android

北城余情 提交于 2019-12-02 12:18:15

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/17496442/changing-menu-item-programmatically-is-not-working-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!