Android: OptionMenu between Activity and Fragments
Asked Answered
O

3

7

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?

Outandout answered 15/3, 2013 at 2:57 Comment(1)
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 methodVoigt
D
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);


}
Drawing answered 15/3, 2013 at 3:11 Comment(3)
It shows 2 menus.. 1 from my activity and 1 in fragment. Do u know how to hide activity menu. which i have in all fragmentsProleg
I think you should not inflate menu in your Activity to avoid that.Drawing
try setting menu.removeItem(R.id.parentMenuItem); in fragment to avoid repetitionOosphere
I
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().

Immutable answered 15/3, 2013 at 4:3 Comment(0)
O
0

I found out that I can add MenuItem in the Activity onCreateOptionsMenu() and then retrieve them in the Fragments 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);                         
}
Outandout answered 16/3, 2013 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.