如何在Android操作栏中隐藏菜单项? [英] How to hide menu item in android action bar?

查看:661
本文介绍了如何在Android操作栏中隐藏菜单项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是隐藏操作栏中的一个菜单项,并在单击菜单项后显示另一个菜单项.在我的应用程序中,我正在使用Toolbar.我已经寻找了许多其他问题,但没有找到我所需要的.任何帮助将不胜感激.我在下面尝试了代码,但是单击后这会使应用程序崩溃.

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);
    }
}

推荐答案

您可以获取要隐藏并显示在onCreateOptionsMenu中的菜单项的引用,然后在:

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);
}

这篇关于如何在Android操作栏中隐藏菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆