menu.findItem(R.id.*) is null- Android

核能气质少年 提交于 2019-12-06 19:56:31

问题


I am trying to enable/disable a refresh button when certain things happen in my app, but I get a null pointer exception that I can't figure out. I am setting a boolean addingRefresh or removingRefresh to true depending on the situation and then calling invalidateOptionsMenu() to enable or disable the button, however the menu item is returned null. I have searched the internet for why this may be but can't find anything.

Code for onCreateOptionsMenu() (called when invalidateOptionsMenu() is called)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (addingRefresh) {
        //below line as well as other similar line cause exceptions
        menu.findItem(R.id.action_refresh).setEnabled(true);
        addingRefresh = false;
    } else if (removingRefresh) {
        menu.findItem(R.id.action_refresh).setEnabled(false);
        removingRefresh = false;
    } else if (addingLoading) {

    }
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

Thanks for any help!


回答1:


Here is some cleaned up code for what you are trying to accomplish:

private MenuItem mMenuItem;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    final MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    mMenuItem = menu.findItem(R.id.action_refresh)
    return true;
}

private void setMenuItemEnabled(boolean enabled) {
    mMenuItem.setEnabled(enabled);
}

Hope that helps!




回答2:


Just for clearing the doubt. You should use

menu.findItem(R.id.menuId);

after inflating the menu




回答3:


for me cause of issue was wrong import: android.widget.SearchView

instead androidx.appcompat.widget.SearchView

and take care about namespaces app:actionViewClass



来源:https://stackoverflow.com/questions/25902946/menu-finditemr-id-is-null-android

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