问题
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