开发者

How to disable and enable menu options on Android?

开发者 https://www.devze.com 2023-03-21 20:25 出处:网络
I\'m trying to disable and enable a menu option but it is showing me the error: Nullpointer exception.

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:

  1. Try to call super.onCreateOptionsMenu(menu)
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号