I want to add an Android option menu in Fragment, how do I do it?

Asked 2 years ago, Updated 2 years ago, 164 views

I'd like to add an option menu to the Fragment group. So we created a class called Menu Fragment, and Fragments including menus inherited this class.

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

Is there a reason why onCreateOptionsMenu is not running in this code?

android android-fragments android-optionsmenu

2022-09-21 22:52

1 Answers

Did you call the super method?

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

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Please put the contents of the menu in this part of the menu here. 
    super.onCreateOptionsMenu(menu, inflater);
}

In this way, you must call super.onCreateOptionsMenu() in the onCreateOptionsMenu.


2022-09-21 22:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.