TheModularMind
TheModularMind

Reputation: 2065

Android: OptionMenu between Activity and Fragments

In my app I have one Activity that hosts two Fragments. If I add a MenuItem to the Menu can I retrive it in my fragments? What's the link between OptionMenu in Activity and OptionMenu in his child fragments?

Upvotes: 7

Views: 8488

Answers (3)

TheModularMind
TheModularMind

Reputation: 2065

I found out that I can add MenuItem in the Activity onCreateOptionsMenu() and then retrieve them in the Fragments by their id, like this:

Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     itemId= 0;
     menu.add(0, itemId, 0, "item");
     return super.onCreateOptionsMenu(menu);
}

Fragment:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    itemId= 0
    MenuItem menuItem= menu.findItem(itemId);                         
}

Upvotes: 0

user1521536
user1521536

Reputation:

You cannot catch the event of the activity's menu in sub fragments. Instead, you can have your fragments implement something like MenuItem.OnMenuItemClickListener. And in your activity's onOptionsItemSelected(MenuItem item) method, you simply call YourFragment.onMenuItemClick().

Upvotes: 0

Shajeel Afzal
Shajeel Afzal

Reputation: 5953

You have to call setHasOptionsMenu(); with the true as the argument passed to it then you can override onCreate options menu.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Enable the option menu for the Fragment
    setHasOptionsMenu(true);
}

If you want to have different optionsMenu for each fragment you will define two different menu xml file and inflate them in the onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    inflater.inflate(R.menu.fragment1_menu, menu);


}

Upvotes: 5

Related Questions