如何隐藏操作栏中的菜单项? [英] How do I hide a menu item in the actionbar?

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

问题描述

我有一个带有菜单项的操作栏.如何隐藏/显示该菜单项?

I have an action bar with a menuitem. How can I hide/show that menu item?

这就是我想要做的:

MenuItem item = (MenuItem) findViewById(R.id.addAction);
item.setVisible(false);
this.invalidateOptionsMenu();

推荐答案

获取一个指向该 item 的 MenuItem,在其上调用 setVisible 调整其可见性,然后调用invalidateOptionsMenu() 对您的活动进行相应调整.

Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly.

更新: MenuItem 不是布局中的常规视图.它有些特别,完全不同.您的代码为 item 返回 null 并导致崩溃.你需要做的是:

Update: A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:

MenuItem item = menu.findItem(R.id.addAction);

这是您应该调用的顺序:首先调用 invalidateOptionsMenu() 然后在 onCreateOptionsMenu(Menu) 中获取对 MenuItem 的引用(通过调用 menu.findItem())并调用setVisible() 就可以了

Here is the sequence in which you should call: first call invalidateOptionsMenu() and then inside onCreateOptionsMenu(Menu) obtain a reference to the MenuItem (by calling menu.findItem()) and call setVisible() on it

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

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