Home » Android » OnCreateOptionsMenu() not called in Fragment

OnCreateOptionsMenu() not called in Fragment

Posted by: admin November 29, 2017 Leave a comment


I have an app which got one activity with 2 fragments placed horizontally.

In my activity I inflated menu using onCreateOptionsMEnu() using which I am able to display actionbar options menu. But when I try to update the action bar menu items from one of my fragment , the onCreateoptionsmenu() is not called.So,I’m not able to update the action bar options menu. Can anyone help me in sorting out this issue.
The code in my activity is as below:


In your fragment’s onCreateView() method, you need to call setHasOptionsMenu(true) to tell the host activity that your fragment has menu options that it wants to add.


If you are using a theme that does not support ActionBar, then OnCreateOptionsMenu() will not be called automatically, even you wrote all Java codes properly.

You can open AndroidManifest.xml, change the value of android:theme to “@android:style/Theme.Holo.Light.DarkActionBar”, or any other themes that support ActionBar.


this worked for me


Simply tell the host activity that your fragment has options menu in its constructor.

public YourFragment() {setHasOptionsMenu(true);}

Although it worked for me, it is discouraged as noted in comment from @aldorain

Applications should generally not implement a constructor. The first
place application code can run where the fragment is ready to be used
is in onAttach(Activity), the point where the fragment is actually
associated with its activity.

So put setHasOptionsMenu(true) in onCreateView() or onAttach() instead.



public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)

//set setHasOptionsMenu(true); in onCreateView Method in fragment