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?
Asked
Active
Viewed 8,375 times
7
-
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 Answers
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
-
2It shows 2 menus.. 1 from my activity and 1 in fragment. Do u know how to hide activity menu. which i have in all fragments – djk Apr 12 '14 at 06:37
-
2I think you should not inflate menu in your Activity to avoid that. – Shajeel Afzal Apr 12 '14 at 11:23
-
try setting menu.removeItem(R.id.parentMenuItem); in fragment to avoid repetition – Faisal Naseer Aug 11 '17 at 10:29
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 Fragment
s 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