Ask Your Question
0

How can I utilize the same menu item multiple times in my activity and fragment with a navigation bar?

asked 2023-06-30 19:35:32 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-30 19:55:01 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-30 19:35:32 +0000

Seen: 9 times

Last updated: Jun 30 '23