调用invalidateOptionsMenu()时,Android SearchView无法正常工作

时间:2017-08-25 11:35:52

标签: android show-hide searchview submenu

我想在搜索视图展开时隐藏一些菜单项,所以这是我使用的代码:

@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不会出现。我无法弄清楚问题是什么。我在堆栈溢出时搜索了类似的问题,但我没有找到解决问题的任何答案,所以欢迎任何帮助

1 个答案:

答案 0 :(得分:2)

您可以尝试此方式隐藏并显示其他选项菜单: -

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