我必须在活动中动态引用 menu.xml 中定义的项目。
我试图通过以下方式引用:
MenuItem homeItem = (MenuItem) findViewById(R.id.home);
homeItem.setIcon(R.drawable.home72);
它引发了以下异常:
03-31 10:39:01.703: E/AndroidRuntime(2463): FATAL EXCEPTION: main
03-31 10:39:01.703: E/AndroidRuntime(2463): java.lang.ClassCastException: com.android.internal.view.menu.ActionMenuItemView cannot be cast to android.view.Menu
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.emg.emgstorelocator.StoreLocatorActivity.onOptionsItemSelected(StoreLocatorActivity.java:133)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.app.Activity.onMenuItemSelected(Activity.java:2534)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:958)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:514)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:99)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.view.View.performClick(View.java:4084)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.view.View$PerformClick.run(View.java:16966)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.os.Handler.handleCallback(Handler.java:615)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.os.Handler.dispatchMessage(Handler.java:92)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.os.Looper.loop(Looper.java:137)
03-31 10:39:01.703: E/AndroidRuntime(2463): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-31 10:39:01.703: E/AndroidRuntime(2463): at java.lang.reflect.Method.invokeNative(Native Method)
03-31 10:39:01.703: E/AndroidRuntime(2463): at java.lang.reflect.Method.invoke(Method.java:511)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-31 10:39:01.703: E/AndroidRuntime(2463): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-31 10:39:01.703: E/AndroidRuntime(2463): at dalvik.system.NativeStart.main(Native Method)
这是在 menu.xml 中定义的:
<item
android:id="@+id/home"
android:showAsAction="always"
android:title="Home"
android:icon="@drawable/home72"/>
<item
android:id="@+id/location"
android:showAsAction="always"
android:title="Locations"
android:icon="@drawable/locations72"/>