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:
Create a separate XML file for the repeated menu item in your res/menu/ directory. Let's call it menu_repeated.xml.
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>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
getMenuInflater().inflate(R.menu.menu_repeated, menu);
return true;
}
@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.
Asked: 2023-06-30 19:35:32 +0000
Seen: 9 times
Last updated: Jun 30 '23