Android: OptionMenu between activity and fragments

In my application, I have one action on which two fragments are placed. If I add MenuItem to the menu, can I extract it in my snippets? What is the relationship between OptionMenu in Activity and OptionMenu in its child fragments?

+5
source share
3 answers

You must call it setHasOptionsMenu();using the trueargument passed to it, then you can override the Create Link 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 Menu parameters for each fragment, you will define two different xml files and inflate them into onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    inflater.inflate(R.menu.fragment1_menu, menu);


}
+5
source

I found out what I can add MenuItemto Activity onCreateOptionsMenu(), and then return them to Fragmentby their identifier, for example:

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);                         
}
0
source

All Articles