Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can create a separate menu XML file for the repeated menu item and inflate it in both your activity and fragment. Here are the steps to follow:

  1. Create a separate XML file for the repeated menu item in your res/menu/ directory. Let's call it menu_repeated.xml.

  2. Add the menu item to the menu_repeated.xml file with a unique ID. For example:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu_item_repeated"
        android:title="Repeated Item"/>
</menu>
  1. In your activity's onCreateOptionsMenu() method, inflate your main menu and the menu_repeated.xml file using MenuInflater. For example:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    getMenuInflater().inflate(R.menu.menu_repeated, menu);
    return true;
}
  1. In your fragment's onCreateOptionsMenu() method, inflate just the menu_repeated.xml file using MenuInflater. For example:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_repeated, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Now you can use the same menu item with the unique ID in both your activity and fragment. You can handle clicks on the repeated menu item in your activity or fragment by overriding onOptionsItemSelected() and checking the ID of the menu item clicked.