Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different menu for different fragments

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?

like image 230
SAIR Avatar asked Feb 11 '14 14:02

SAIR


People also ask

How many types of fragments are there in Android?

The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for fragment.

How are activities different than fragments?

Activity is an application component that gives a user interface where the user can interact. The fragment is only part of an activity, it basically contributes its UI to that activity. Fragment is dependent on activity. It can't exist independently.

Can fragments be used in multiple activities?

You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment. With this in mind, you should only provide a fragment with the logic necessary to manage its own UI.


2 Answers

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

like image 58
BigT Avatar answered Nov 15 '22 16:11

BigT


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.

like image 36
gunar Avatar answered Nov 15 '22 16:11

gunar