问题
I'm stuck while changing some properties on my options menu at onCreateOptionsMenu()
. It seems like findItem() returns null, even though I'm pretty sure that the reference to the menu item is correct. My code looks as follows:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_profile, menu);
MenuItem leftie = menu.findItem(R.id.menu_profile);
leftie.setIcon(R.drawable.ic_menu_mapmode);
leftie.setTitle(R.string.back_map);
leftie.setIntent(authIntent);
return true;
}
I really don't know what can be wrong there. Thanks in advance :)
EDIT: I forgot to include the actual problem.
回答1:
You can mention title and image for that menu item in XML.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/newsItem"
android:icon="@drawable/news_tab"
android:title="@string/menu_news"/>
<item
android:id="@+id/dryiceItem"
android:icon="@drawable/dryice_tab"
android:title="@string/menu_dryice"/>
</menu>
and can set intent on menuItem like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.newsItem:
// start News activity
//write your intent here.
break;
case R.id.dryiceItem:
//start another activity
//write your intent here.
break;
}
}
回答2:
I figured it out. The String that references to the menu
index, R.menu.activity_profile
was the wrong path so it was inflating an empty menu. I changed the string to R.menu.layout
and now it works as expected.
System.out.println(menu.size());
MenuItem leftie = menu.findItem(R.id.menu_profile);
System.out.println(leftie);
leftie.setIcon(R.drawable.ic_menu_mapmode);
leftie.setTitle(R.string.back_map);
leftie.setIntent(authIntent);
回答3:
I've also had this happen when I had a submenu that wasn't properly nested in item tags, like
<item />
<menu>
</menu>
or
<item >
<menu>
</menu>
<item>
回答4:
Typecast your findItem statement with MenuItem
MenuItem leftie = (MenuItem) menu.findItem(R.id.menu_profile);
来源:https://stackoverflow.com/questions/12946379/finditem-doesnt-find-menu-stuck-with-nullpointerexception