[android] onCreateOptionsMenu inside Fragments

I have placed setHasOptionsMenu(true) inside onCreateView, but I still can't call onCreateOptionsMenu inside fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                         Bundle savedInstanceState) {   
   setHasOptionsMenu(true);             
   return inflater.inflate(R.layout.facesheet, container, false);
}

Below is my onCreateOptionsMenu code.

@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    getSupportMenuInflater().inflate(R.menu.layout, menu);
    return (super.onCreateOptionsMenu(menu));
}

The error message I get:

The method onCreateOptionsMenu(Menu) of type Fragment must override or implement a supertype method.

The answer is


Call

setSupportActionBar(toolbar)

inside

onViewCreated(...) 

of Fragment

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((MainActivity)getActivity()).setSupportActionBar(toolbar);
    setHasOptionsMenu(true);
}

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_add_customer, container, false);
        setHasOptionsMenu(true);
}

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

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.


Your already have the autogenerated file res/menu/menu.xml defining action_settings.

In your MainActivity.java have the following methods:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_settings:
            // do stuff, like showing settings fragment
            return true;
    }

    return super.onOptionsItemSelected(item); // important line
}

In the onCreateView() method of your Fragment call:

setHasOptionsMenu(true); 

and also add these 2 methods:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.fragment_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_1:
            // do stuff
            return true;

        case R.id.action_2:
            // do more stuff
            return true;
    }

    return false;
}

Finally, add the new file res/menu/fragment_menu.xml defining action_1 and action_2.

This way when your app displays the Fragment, its menu will contain 3 entries:

  • action_1 from res/menu/fragment_menu.xml
  • action_2 from res/menu/fragment_menu.xml
  • action_settings from res/menu/menu.xml

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to layout-inflater

onCreateOptionsMenu inside Fragments How does the getView() method work when creating your own custom adapter? Call to getLayoutInflater() in places not in activity How to change the Text color of Menu item in Android? What does LayoutInflater in Android do? How to change the background color of the options menu? How to inflate one view with a layout

Examples related to oncreateoptionsmenu

onCreateOptionsMenu inside Fragments