Searchview clear focus on hide keyboard

Viewed 646

The user presses the hide keyboard button or the back button. So I need to clear focus on the SearchView when the user is hiding the keyboard.

I tried this but it's not working. focus remains when the user hides the keyboard.

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                app.requests.getApi().search(newText).enqueue(SearchFragment.this);
                return false;
            }
        });

and this:

searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    app.functions.logWrite("has focus to searchview");
                } else {
                    //code
                }
            }
        });
2 Answers

Okay so try this it needs the use of a library unfortunately but it makes it easier.

In your build.gradle: add this:

dependencies {
    implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC2'
}

Register for the keyboard events using KeyboardVisibilityEvent library like this in the fragment/class where SearchView is declared:

KeyboardVisibilityEvent.setEventListener(
    getActivity(),
    new KeyboardVisibilityEventListener() {
        @Override
        public void onVisibilityChanged(boolean isOpen) {
            if (!isOpen) {
               View focusedView = getWindow().getCurrentFocus();
               if (focusedView != null && focusedView instanceof SearchView) { // does SearchView have focus?
                    searchView.clearFocus();
                }
            }
        }
    });

searchView.clearFocus(); works on the assumption you have another focusable view in the hierarchy, if not add this to your fragments layout:

android:focusableInTouchMode="true"

Alternatively simply call focus(); on any other view element you want to receive focus.

This is what I use for handling back button clicks for SearchView, by Overriding onBackPressed()

@Override
    public void onBackPressed() {
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
            ANY_VIEW_IN_YOUR_LAYOUT.requestFocus();
        } else
            super.onBackPressed();
    }

Hope this helps. Feel free to ask for clarifications...

Related