'onPrepareOptionsMenu Duplicates item in ActionBar
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
Solution 1:[1]
onPrepareOptionsMenu is called every time before menu is shown.
Use menu.clear() in onPrepareOptionsMenu(), and then add new menu item.
Solution 2:[2]
Cheking menu size before inflating it worked for me
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
if (menu.size == 0) {
activity?.menuInflater?.inflate(R.menu.menu_filter, menu)
}
// ...
}
Solution 3:[3]
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
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
//menu.clear();
if(menu.size() == 1) {
// inflater.inflate(R.menu.dashboard_main,menu);
MenuItem mit = menu.add("Refresh");
mit.setIcon(android.R.drawable.stat_notify_sync);
mit.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lynn8570 |
| Solution 2 | Temur Isroilov |
| Solution 3 | Akah |
