Android: OptionMenu between Activity and Fragments

TheModularMind picture TheModularMind · Mar 15, 2013 · Viewed 7.9k times · Source

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?

Answer

Shajeel Afzal picture Shajeel Afzal · Mar 15, 2013

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


}