android - findItem() returns null for 1 of 3 menu items -
this xml document define menu:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/search" android:icon="@drawable/ic_action_search" android:showasaction="ifroom" android:title="@string/search"/> <item android:id="@+id/locate" android:icon="@drawable/ic_action_locate" android:showasaction="ifroom" android:title="@string/locate"/> <item android:id="@+id/favorite" android:icon="@drawable/ic_action_star" android:showasaction="ifroom" android:title="@string/favorite"/> </menu>
and here's assign menu items variables (mainmenu
private variable gets set in oncreateoptionsmenu()
):
menuitem favorite = mainmenu.finditem(r.id.favorite); menuitem search = mainmenu.finditem(r.id.search); menuitem locate = mainmenu.finditem(r.id.locate);
this results in 2 of variables being assigned identifiers, , 1 variable being assigned null
. in cases, null variable corresponds menu item defined second in xml file (in case, locate
). if move locate
after favorite
in xml, favorite
null. order in 3 variables assigned in java doesn't matter.
i'm flummoxed. missing?
you may try cast object :
menuitem favorite = (menuitem)mainmenu.finditem(r.id.favorite);
nervetheless, if want perform actions on items can override method onoptionsitemselected
.
@override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.search: // stuff break; case r.id.locate: //stuff break; case r.id.favorite: //stuff break; default: break; } }
Comments
Post a Comment