我想在搜索视图展开时隐藏一些菜单项,所以这是我使用的代码:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_refresh).setVisible(!isSearchOpen)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchMenuItem = menu.findItem(R.id.action_search)
SearchView searchView = searchMenuItem.getMenu();
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
isSearchOpen = true;
invalidateOptionsMenu();
return true;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
isSearchOpen = false;
invalidateOptionsMenu();
return true;
}
});
}
现在,此代码按预期工作,除了一个问题:当我单击搜索按钮时,SearchView 没有出现。我无法弄清楚问题出在哪里。我在堆栈溢出上搜索了类似的问题,但我没有找到任何解决此问题的答案,因此欢迎任何帮助
您可以尝试这种方式隐藏和显示其他选项菜单:-
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
final MenuItem delMenu = menu.findItem(R.id.action_delete);
final MenuItem editMenu = menu.findItem(R.id.action_edit);
MenuItem searchMenu = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchMenu.getActionView();
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if(b) {
delMenu.setVisible(false);
editMenu.setVisible(false);
}
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
delMenu.setVisible(true);
editMenu.setVisible(true);
return false;
}
});
return true;
}