Jay Gunawardena
Jay Gunawardena

Reputation: 65

onCreateOptionsMenu isn't being called inside Fragments

I know that this question has been asked quite a few times since I searched all over for an answer, but, sadly, I failed to find an answer mainly due to the fact that no one seems to be using the base Android classes for Fragments & instead they all use the Sherlock Fragment Class.

So first of all, I am not using any Sherlock Activity stuff or the Android Support Library. I'm just using the default Fragment class:

import android.app.Fragment
import android.view.Menu
import.android.view.MenuItem
import.android.view.View
//& so on...

This is onCreateView inside my Fragment

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

& this is onCreateOptionsMenu also inside the same Fragment

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getActivity().getMenuInflater();
    menu.clear();
    inflater.inflate(R.menu.fragment1_menu, menu);

//A lot of other code here

return super.getActivity().onCreateOptionsMenu(menu);

}

My base Main FragmentActivity class doesn't have an onCreateOptionsMenu itself but I don't suppose that, that should affect the Fragments.

Also, I cannot seem to override onCreateOptionsMenu, the error I get is; onCreateOptionsMenu must override or implement a supertype method.

So please if anyone has any ideas that could resolve this, I'd really appreciate it!

Thank you so much!

Upvotes: 1

Views: 1952

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007554

The method signature for onCreateOptionsMenu() is different in a Fragment than in an Activity, as is shown in the documentation.

Change your implementation to:

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

   //A lot of other code here

   super.onCreateOptionsMenu(menu, inflater);
}

Upvotes: 3

Related Questions