Reputation: 21
I have a main activity along with 3 fragments. I am using navigation drawer to select these fragments. I want to edit the overflow menu options in the action bar based on the fragment currently being shown. For example: If Fragment A is being shown now, i would like to have Edit,Sign Out and Settings options under the overflow button. If Fragment B is selected now, i should have only Settings there.
I tried to override the onCreateOptionsMenu() in the main activity with a different xml and in the fragment with a different one but it does not help as only the options in main activity are shown.
In Main Activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//return true;
return super.onCreateOptionsMenu(menu);
}
In Fragment A:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.menu1, menu);
//return true;
return true;
}
main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_signout"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Sign Out"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
menu1.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_edit"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Edit Profile"/>
<item
android:id="@+id/action_signout"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Sign Out"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
Upvotes: 0
Views: 4369
Reputation: 3922
To override options menu you should use setHasOtionsMenu(true) and
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
That's it
Upvotes: 0
Reputation: 5248
Call setHasOptionsMenu(true)
in your Fragment's onCreate()
.
public void setHasOptionsMenu (boolean hasMenu)
Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods.
If
hasMenu
is true, the fragment has menu items to contribute.
To hide a particular MenuItem you can call setVisible(false)
on it in onPrepareOptionsMenu()
. For example:
@Override
public void onPrepareOptionsMenu(Menu menu) {
//Hides MenuItem action_edit
menu.getItem(R.id.action_edit).setVisible(false);
}
Upvotes: 0