How to hide menu item in android action bar?

旧城冷巷雨未停 提交于 2020-05-11 07:42:27

问题


My goal is to hide one of the menu items in the action bar and show another after clicking on menu item. In my application, i am using Toolbar. I have already looked for many other questions and did not find what I needed. Any help will be appreciated. I tried code below, but this crashes app after click.

public boolean onOptionsItemSelected(MenuItem item) {
    final SwipeRefreshLayout mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    switch (item.getItemId()) {
        case R.id.action_next:
            //code
            MenuItem secondItem = (MenuItem) findViewById(R.id.action_next);
            secondItem.setVisible(false);
            return true;

        case R.id.action_previous:
            //code
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

回答1:


You can get a reference to the menu items which you would like to hide and show in onCreateOptionsMenu and then make one visible and the other invisible inside onOptionsItemSelected :

private MenuItem itemToHide;
private MenuItem itemToShow;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    itemToHide = menu.findItem(R.id.item_to_hide);
    itemToShow = menu.findItem(R.id.item_to_show);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_next:
            // hide the menu item
            itemToHide.setVisible(false);
            // show the menu item
            itemToShow.setVisible(true);
            return true;
    }      

    return super.onOptionsItemSelected(item);
}



回答2:


You are overriding the wrong function.

use this:

    @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu, menu);
    MenuItem item = menu.findItem(R.id.action_next);
    item.setVisible(false);   //hide it
    super.onCreateOptionsMenu(menu, inflater);
}


来源:https://stackoverflow.com/questions/42890528/how-to-hide-menu-item-in-android-action-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!