【问题标题】:How to hide menu item in android action bar?如何在android操作栏中隐藏菜单项?
【发布时间】:2017-03-20 14:56:31
【问题描述】:
我的目标是在操作栏中隐藏一个菜单项,并在单击菜单项后显示另一个。在我的应用程序中,我使用的是Toolbar。我已经寻找了许多其他问题,但没有找到我需要的东西。任何帮助将不胜感激。我尝试了下面的代码,但是点击后应用程序崩溃了。
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);
}
}
【问题讨论】:
标签:
android
android-actionbar
toolbar
【解决方案1】:
您可以在onCreateOptionsMenu 中获取要隐藏和显示的菜单项的引用,然后在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】:
你重写了错误的函数。
使用这个:
@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);
}