android – 在导航抽屉活动布局上启用和禁用MenuItem

我有和使用导航抽屉Activity布局创build的应用程序。我需要以编程方式启用/禁用一些项目

菜单示例

例如:我想禁用Menu Item id nav_item2

我试图做…

 MenuItem nav_item2 = (MenuItem)findViewById(R.id.nav_item2); nav_item2.setEnabled(false); 

它返回一个NullPointerException给我..

也试过…

 @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); nav_item2 = menu.findItem(R.id.nav_item2); return true; } 

NullPointerException相同

有人知道该怎么办?

nav_header_main_activity.xml(由版面创build生成)

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height" android:background="@drawable/side_nav_bar" android:gravity="bottom" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:theme="@style/ThemeOverlay.AppCompat.Dark"> <ImageView android:id="@+id/imageView" android:layout_width="199dp" android:layout_height="72dp" android:paddingTop="@dimen/nav_header_vertical_spacing" android:src="@drawable/ciag" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/nav_header_vertical_spacing" android:text="CIAg" android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="dev@ciag.org.br" /> </LinearLayout> 

main_activity_navigation_drawer.xml(在布局创build时生成)

 <group android:checkableBehavior="single"> <item android:id="@+id/nav_save" android:icon="@android:drawable/ic_menu_save" android:enabled="false" android:title="@string/nav_save" /> <item android:id="@+id/nav_graph" android:icon="@drawable/chart_bar" android:enabled="false" android:title="@string/nav_graph" /> <item android:id="@+id/nav_send" android:icon="@drawable/ic_menu_send" android:title="Enviar" /> </group> <item android:title="Configurações"> <menu> <item android:id="@+id/nav_manage" android:icon="@drawable/ic_menu_manage" android:enabled="false" android:title="@string/nav_manage" /> <item android:id="@+id/nav_support" android:icon="@android:drawable/ic_menu_help" android:title="@string/nav_support" /> </menu> </item> 

Solutions Collecting From Web of "android – 在导航抽屉活动布局上启用和禁用MenuItem"