How to disable and enable menu options on Android?
I'm trying to disable and enable a menu option but it is showing me the error: Nullpointer exception.
Here is my code:
mnu.xml:
开发者_开发问答<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Add" android:title="Add" android:icon="@drawable/add"/>
<item android:id="@+id/bill_menu" android:title="Bill" android:enabled="false" />
</menu>
I used in my java class
//creating menu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnu, menu);
MenuItem mi=((MenuItem) this.findViewById(R.id.bill_menu));
mi.setEnabled(true);
}
return true;
}
Replace
MenuItem mi=((MenuItem) this.findViewById(R.id.bill_menu));
with
MenuItem mi = menu.findItem(R.id.bill_menu);
In order to disable options menu - override onPrepareOptionsMenu() and return false as described in onPrepareOptionsMenu().
Some suggestions regarding exception:
- Try to call super.onCreateOptionsMenu(menu)
- Determine which is actually null and share logcat output.
Wouldn't it be better if you override the onCreateOptionsMenu() and add your menu items there and override the onPrepareOptionsMenu() to change the enabling of your items. This will lower the chances of errors in your code and you will no longer have the problem you are having right now.
精彩评论