Fragment not receiving menu callbacks

aromero picture aromero · Jun 8, 2011 · Viewed 26.6k times · Source

I have a fragment class that extends Fragment and calls setHasOptionsMenu to participate in the menu. This class also implements onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected.

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

I'm dynamically loading this fragment using a FragmentTransaction in my Activity (that extends FragmentActivity).

However none of the menu callbacks (onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected) are being called (I've debugged with some breakpoints in those methods) and the menu isn't shown.

Am I missing something? Do I need to add something in my Activity?

I'm using the Android Compatibility Library, compiling with L11 SDK and testing in a Xoom.

EDIT: I've found the problem. My AndroidManifest is targeting L11, this seems to hide the menu button and prevent from the callbacks being called. However if I remove this from the manifest I loose some other features I need (for example the activated state in lists). Does anyone know how to solve this issue (enable the menu button) without removing the targetSdkVersion=11 from the Manifest?

Answer

user553456 picture user553456 · Jun 8, 2011

Aromero, Don't forget to override the onCreateOptionsMenu using the fragment version of the method, similar to this:

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

This goes in the fragment, by the way, and adds to the inflated menu of the Activity, if there is one. Had the same problem myself, until I figured this out.

Kim