How to access an Android MenuItem from a Java Activity or Fragment

Here’s a quick example of how to access an Android MenuItem in a Java Activity or Fragment class (i.e., in your Java code).

Given a menu named res/menu/menu_landing_page.xml that’s defined in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:myapp="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/menuItemPinQuote"
          android:icon="@drawable/ic_action_place"
          android:title="@string/menu_landing_page_pin"
          myapp:showAsAction="ifRoom|withText" />

</menu>

you can access the MenuItem with the id menuItemPinQuote like this in your Android/Java code:

public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
    menuInflater.inflate(R.menu.menu_landing_page, menu);
    super.onCreateOptionsMenu(menu, menuInflater);

    MenuItem pinMenuItem = menu.findItem(R.id.menuItemPinQuote);
    ...
    ...
    ...
}

Once you have a reference to the MenuItem in your Java code, you can do whatever you need to do with it. For instance, I wanted to make my menu item visible or invisible depending on a certain state, which I can now do like this:

pinMenuItem.setVisible(false);

In my fast Android browser app I update the menu item text like this:

homePageMenuItem.setTitle(HOME_MENU_ITEM_SET_HOME_PAGE);

So, in summary, if you needed to see how to access an Android MenuItem from your Java Activity or Fragment code, I hope this is helpful.