Home » Android » OnCreateOptionsMenu() not called in Fragment

OnCreateOptionsMenu() not called in Fragment

Posted by: admin November 29, 2017 Leave a comment

Questions:

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:
myActivity.java
===============

Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

this worked for me

Questions:
Answers:

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.

Questions:
Answers:

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
Viewroot=inflater.inflate(R.layout.fragment_client_requestfragment,container,false);
hideKeyboard();

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