Changing visibility of menu items in fragment

2019-08-26 12:56发布

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?

2条回答
放我归山
2楼-- · 2019-08-26 13:16

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 (or supportInvalidateOptionsMenu for actionbar compat), it will force the onCreateOptionMenu to be called again and you can update the menu if the fragment is there or not.

查看更多
我只想做你的唯一
3楼-- · 2019-08-26 13:23

in your fragment 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);
    }
查看更多
登录 后发表回答