如何关闭一个搜索查看编程? [英] How do I close a SearchView programmatically?

查看:139
本文介绍了如何关闭一个搜索查看编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有我的应用程序的操作栏搜索查看。当我点击搜索图标,在搜索查看扩展和键盘弹出预期。点击和SearchView框的X如预期关闭和SearchView。然而,当搜索查看被激活,我preSS的后退按钮,我的应用程序退出。这是正确的行为,但是我想现在要做的就是捕捉后退按钮preSS,只是把它关闭搜索查看(不是我的应用程序),当搜索查看可见。有没有一种方法来调用搜索查看OnCloseListener()编程上的后退按钮preSS?举例来说,这样的事情:

  //在后退按钮preSS,如果我们当前搜寻,
//关闭搜索查看。否则,调用正常返回按钮
// 行为。
公共布尔的onkeydown(INT键code,KeyEvent的事件){
   如果(键code == KeyEvent.KEY code_BACK){
        如果(isSearchViewVisible){
            搜索查看搜索查看=(搜索查看)menu.findItem(R.id.searchBox)
               .getActionView();

            //该方法不存在
            sea​​rchView.invokeClose();
            返回true;
        }
    }
    返回super.onKeyDown(键code,事件);
}
 

解决方案

要拦截BACK按钮覆盖 onBack pressed()see文档

  @覆盖
公共无效onBack pressed(){

    如果(isSearchViewVisible){
        搜索查看搜索查看=(搜索查看)menu.findItem(R.id.searchBox)
           .getActionView();

        //该方法不存在
        sea​​rchView.invokeClose();
    } 其他 {
        super.onBack pressed();
    }
}
 

修改

文档说

  如果有必要

,你可以展开或折叠动作视图在自己的   code。通过在调用expandActionView()和collapseActionView()   菜单项。

I currently have a SearchView in the action bar of my app. When I click the search icon, the SearchView expands and the keyboard pops up as expected. Clicking the "X" in the SearchView box closes the SearchView as expected. However, when the SearchView is activated and I press the "back" button, my app is exited. This is the correct behavior, but what I am trying to do now is to capture back button press and just have it close the SearchView (not my app) when the SearchView is visible. Is there a way to invoke the SearchView OnCloseListener() programmatically on a back button press? For example, something like this:

// On a back button press, if we are currently searching,
// close the SearchView. Otherwise, invoke normal back button
// behavior.
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (isSearchViewVisible) {
            SearchView searchView = (SearchView) menu.findItem(R.id.searchBox)
               .getActionView();

            // This method does not exist
            searchView.invokeClose();
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

解决方案

To intercept BACK button override onBackPressed() (see docs)

@Override
public void onBackPressed() {

    if (isSearchViewVisible) {
        SearchView searchView = (SearchView) menu.findItem(R.id.searchBox)
           .getActionView();

        // This method does not exist
        searchView.invokeClose();
    } else {
        super.onBackPressed();
    }
}

EDIT:

Docs say:

If necessary, you can expand or collapse the action view in your own code by calling expandActionView() and collapseActionView() on the MenuItem.

这篇关于如何关闭一个搜索查看编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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