Android: How to unfocus a SearchView programmatica

2019-07-02 00:32发布

I have a SearchView in my layout (not in the action bar) and I'm unable to dismiss the keyboard using the usual method:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager)activity
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm != null && activity != null) {
        View currentFocus = activity.getCurrentFocus();

        if (currentFocus != null) {
            imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
        }
    }
}

The SearchView maintains its focus state. Using this method on older devices shows the keyboard being dismissed then redisplaying.

I believe the issue is with the fact that a SearchView is actually a hierarchy of Views that maintain their own state internally.

How do I dismiss the keyboard and unfocus the SearchView?

1条回答
Melony?
2楼-- · 2019-07-02 01:05

It sounds like what might be happening is that you're unfocusing the SearchView and then it's saying "oh wait, I still have focus, I need the keyboard". Does activity.getCurrentFocus().clearFocus() clear out the focus?

查看更多
登录 后发表回答