Home » Android » android – Different menu for different fragments

android – Different menu for different fragments

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have an activity which has 2 fragments.
1 fragment is visible at a time and each fragment has a different option menu.

I can achieve this behavior by 2 different ways.

1 – I can add different menu for each fragment by calling onCreateOptionsMenu in each friengment.
2 – I can have only one menu at activity level and can select to show particular option in onPrepareOptionsMenu

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

How to&Answers:

I would follow the first option as having a dedicated resource menu for each fragment seems cleaner and also reduces the code complexity you would have in order to maintain what is visible and what is not (if you would go through onPrepareOptionsMenu and have code to hide & show different menus).

If you have some actions in your fragments, then you could create a base fragment class that each of your fragments would extend from.

Answer:

Hope this helps

Adding items to the Action Bar

Your fragments can contribute menu items to the activity’s Options Menu (and, consequently, the Action Bar) by implementing onCreateOptionsMenu(). In order for this method to receive calls, however, 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 a call to onCreateOptionsMenu()).

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

You can also register a view in your 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