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?
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);
}
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()
.
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);
}
© 2022 - 2024 — McMap. All rights reserved.