misterbassman misterbassman - 5 months ago 79
Android Question

Android Options Menu in Fragment

I am trying to add an item to the options menu from a group of fragments.

I have created a new

MenuFragment
class and extended this for the fragments I wish to include the menu item in. Here is the code:

public class MenuFragment extends Fragment {

MenuItem fav;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
fav = menu.add("add");
fav.setIcon(R.drawable.btn_star_big_off);
}
}


For some reason the
onCreateOptionsMenu
appears not to run.

Answer

Call the super method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // TODO Add your menu entries here
    super.onCreateOptionsMenu(menu, inflater);
}

Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.

Also ensure you are calling SetHasOptionsMenu in onCreate to notify the fragment that it should participate in options menu handling.

Comments