I have a Toolbar
being used as an ActionBar
with two items. I only want to ever display one at a time as they kind of replace each other. The problem is that when i replace a Fragment
, it call onCreateOptionsMenu
and will inflate the menu again, meaning that the same action button will be shown, even if the other one was previously in the ActionBar
. I have to need to change anything in the ActionBar
from my Fragments
or when a new Fragment
is displayed(with FragmentManager.FragmentTransaction.replace()
). So my question is how do I not call onCreateOptionsMenu
when a new fragment is displayed?
I can't use a boolean
because I will still need it to reinflate on orientation change. And any advice on how to handle orentation change for my situation?
I can post code, but it seems more conceptual and I'm not sure that it would help.
I solved the problem by instead of not calling onCreateOptionsMenu
, I added the items to my menu manually.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean refreshVisible;
if (refreshItem != null && refreshItem.isVisible()){//is being displayed prior to inflation
refreshVisible = true;
}else if (refreshItem == null){//it's null so the menu has never been created
refreshVisible = true;
}else {//it's not null and invisibe, other icon was being displayed
refreshVisible = false;
}
menu.clear();//clear menu so there are no duplicate or overlapping icons
getMenuInflater().inflate(R.menu.main, menu);//inflate menu
refreshItem = menu.findItem(R.id.refresh);
useDataItem = menu.findItem(R.id.use_data);
refreshItem.setVisible(refreshVisible);//if menu is being created for first time or item was previously visible, then display this item
useDataItem.setVisible(!refreshVisible);//display this item if not displaying other
return true;
}