When I add a menu item using onPrepareOptionsMenu, the menu item duplicates its self in the action bar. I'm using fragments and creating the initial menu in the ActionBar in the main activity like this:
...
@Override
public boolean onCreateOptionsMenu(Menu paramMenu) {
super.onCreateOptionsMenu(paramMenu);
paramMenu.add(0, 1, 0, "DashBoard").setIcon(R.drawable.ic_dashboard)
.setShowAsAction(1);
return true;
}
I'm then adding another item in one of the fragments as follows:
...
@Override
public void onPrepareOptionsMenu(Menu paramMenu) {
paramMenu.add(0, 2, 1, "FullScreen").setIcon(R.drawable.ic_fullscreen)
.setShowAsAction(1);
}
For some reason this added item via the fragment class displays twice.... Do i have something wrong?
Any help to what I have wrong will be appreciated
onPrepareOptionsMenu
is called every time before menu is shown.Use
menu.clear()
inonPrepareOptionsMenu
(), and then add new menu item.The item is probably displaying twice because you're adding it twice. See the docs for
onPrepareOptionsMenu
:I really wouldn't blindly add an item in
onPrepareOptionsMenu
ever. You should check if it's already been added first.I use fragments within an activity and i use swipe to switch between them. My main activity has some menu items, but i use my fragment to dynamically add one at runtime, i.e when the fragment becomes visible. My fragament's oncreateOptions method is as shown below: The menu item appears now only once
Another possible fix is that you could add fragments to your activity only when the instancestate bundle is null, because by then, your activity would have discarded the fragment and as such , it is necessary for it to be recreated with its menu items.