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?
I've found the problem. The AndroidManifest is targeting SDK 11, this seems to hide the menu button and prevent from the callbacks being called. I assume that this breaks the compatibility of the menu button that seems to be replaced by the action bar in Android 3.0
From the android developer site - link
Therefore Marco HC is the best answer of all.
If you have an activity and a fragment that each loads menu items then you need to take special care of which overrides you use.
Activities can override onOptionsItemSelected and onMenuItemSelected, however fragments can only override onOptionsItemSelected.
If you override onMenuItemSelected in your activity and onOptionsItemSelected in your fragment, your fragment override will never get triggered.
Instead, use onOptionsItemSelected in both activity and fragment.
If your toolbar is defined in the parent activity xml, make sure you do this in your fragment
And then of course, override onCreateOptionsMenu like below
This is the only solution that worked for me!
I think you have implemented
onCreateOptionsMenu
,onPrepareOptionsMenu
andonOptionsItemSelected
in the class thatextends Fragment
. Try by doing that in your Activity class where you are loading this fragmentYou need to make sure you call
setHasOptionsMenu(true);
onCreate
oronCreateView
is called in your fragment.You also need to implement the override of
onCreateOptionsMenu
inside your fragment.