Change the visibility of menu items in a fragment

I try to hide some menu items when the fragment is changed, but it seems that this does not work. Here's what I do: Defining menus 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; } 

fragment change and visibility change:

  //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 changing the fragment, I still see the menu item. Can someone help me with a decision on how to do this?

0
source share
2 answers

I do not know why this does not work, but try changing the visibility directly in onCreateOptionMenu .

If this works, then when you want to hide it, call invalidateOptionsMenu (or supportInvalidateOptionsMenu for compatibility with the action bar), it will force onCreateOptionMenu to be called again, and you can refresh the menu if there is a fragment or not.

0
source

in your snippet add below code

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_cart).setVisible(false); menu.findItem(R.id.action_search).setVisible(false); menu.findItem(R.id.overflow).setVisible(false); } 
0
source

Source: https://habr.com/ru/post/1207666/


All Articles