Different menu for different fragments

I have an activity that has 2 fragments.
1 fragment is displayed simultaneously, and each fragment has a different options menu.

I can achieve this behavior in two different ways.

1 - I can add another menu for each fragment by calling onCreateOptionsMenu in each of them. 2 - I can have only one menu at the activity level and you can choose to show a specific option in onPrepareOptionsMenu

What I want to know:
What is the preferred way to implement this functionality? What is recommended?

+7
android android-fragments menu
source share
2 answers

I would use the first option, since having a dedicated resource menu for each fragment seems to be cleaner, and also reduces the complexity of the code that you will have to support what is visible and what is not (if you go through onPrepareOptionsMenu and have code for hiding and displaying different menus).

If you have any actions in your fragments, you can create a base class of fragments from which all your fragments will come out.

+3
source share

Hope this helps

Adding items to the action bar

Your fragments can add menu items to the action parameter menu (and therefore to the action bar) by implementing onCreateOptionsMenu (). However, in order for this method to accept calls, you must call setHasOptionsMenu () during onCreate () to indicate that the fragment would like to add items to the options menu (otherwise the fragment will not receive the call onCreateOptionsMenu ()).

Any items that you then add to the options menu from the fragment are added to existing menu items. The snippet also receives onOptionsItemSelected () callbacks when a menu item is selected.

You can also register a view in a fragment layout to provide a context menu by calling registerForContextMenu (). When the user opens the context menu, the fragment receives a call to onCreateContextMenu (). When the user selects an item, the fragment receives a call to onContextItemSelected ().

http://developer.android.com/guide/components/fragments.html

+7
source share

All Articles