finditem() doesn't find menu, stuck with NullPointerException

时光毁灭记忆、已成空白 提交于 2019-12-10 17:52:11

问题


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

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