I am currently working on an android project and I am having a bit of a strange issue. Its probably something really simple I’m missing but can’t see what I’ve done wrong.
I’ve added a new menu item to my XML file and then I am trying to reference the new menu item to either show it or hide it. The menu item is being shown on the screen when I run the app so I know I have the XML correct and have the correct file but when I try and do findViewById it returns null.
Below is the code.
MenuItem mnuUpgrade;
mnuUpgrade = (MenuItem)findViewById(R.id.mnu_upgrade);
if (common.checkForProVersion())
{
//mnuUpgrade.setVisible(false);
}
else
{
//mnuUpgrade.setVisible(true);
}
and below is my XML file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/mnu_addLogin"
android:title="New Login"
android:icon="@android:drawable/ic_menu_add"
android:showAsAction="always">
</item>
<item android:id="@+id/mnu_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="always">
</item>
<item android:id="@+id/mnu_settings"
android:title="Settings"
android:showAsAction="ifRoom"
android:icon="@android:drawable/ic_menu_manage">
</item>
<item android:id="@+id/mnu_upgrade"
android:title="Upgrade"
android:showAsAction="ifRoom"
android:icon="@android:drawable/ic_menu_upload">
</item>
<item android:id="@+id/mnu_logout"
android:title="Log out"
android:showAsAction="ifRoom"
android:icon="@android:drawable/ic_menu_close_clear_cancel">
</item>
</menu>
Thanks for any help you can provide.
The
findViewByIdcan’t find a MenuItem. You can use theonPrepareOptionsMenuin your activity. It’s called when user tries to open the menu. You can try this: