7

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?

TheModularMind
  • 2,024
  • 2
  • 22
  • 36
  • Whats the reason for wantin to retrieve the menuItem in the fragments ? Usually you just want to add to the menu from the fragments and thats just a matter of overriding onCreateOptionsMenu in the fragments and calling setHasOptionsMenu(true) in their onCreate method – Marco RS Mar 15 '13 at 03:01

3 Answers3

5

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);


}
Shajeel Afzal
  • 5,913
  • 6
  • 43
  • 70
0

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().

0

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);                         
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
TheModularMind
  • 2,024
  • 2
  • 22
  • 36