I'm trying to hide some menu items when a fragment is changed, but seems that this is not working. Here is what im doing: Defining the menu and menu items:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actionbar_sharecall, menu);
actionMenu = menu;
MenuItem searchItem = menu.findItem(R.id.action_searchmenuitem);
MenuItem item = menu.findItem(R.id.action_menushare);
// item.setVisible(false);
// searchItem.setVisible(false);
topSearch = searchItem;
topShare = item;
final MRShareActionProvider actionProvider = new MRShareActionProvider(
this);
MenuItemCompat.setActionProvider(item, actionProvider);
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
actionProvider.setOnShareTargetSelectedListener(this);
actionProvider.setShareIntent(createShareIntent());
return true;
}
changing the fragment and changing the visibility:
//changing visibility
topSearch.setVisible(false);
frag = new SyncFragment();
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.fragment_content, frag);
ft.commitAllowingStateLoss();
and this is my SyncFragment:
public class SyncFragment extends MRBaseACBFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sync, null);
}
}
but after the fragment is changed, i can still see the menu item. Can someone help me with a solution on how to do this?
I don't know why it does not work, but try to change the visibility directly in the
onCreateOptionMenu
.If it works, then when you want to hide it call
invalidateOptionsMenu
(orsupportInvalidateOptionsMenu
for actionbar compat), it will force theonCreateOptionMenu
to be called again and you can update the menu if the fragment is there or not.in your fragment add below code