6

I am building android Application in which i have embedded a searchview below toolbar. See Screenshot. But when i click on the search icon my keyboard appears but when i click close icon of searchview, keyboard does not disappear. Close listener is not working and action expand or collapse listener can not be used because it is not a menuitem. So how should i disappear the keyboard. Please guide.

enter image description here

 simpleSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            hideKeyboard(getActivity());
            return false;
        }
    });
shivani gupta
  • 235
  • 4
  • 20

1 Answers1

9

You can do this by getting a reference to the [x] button, then setting an onClick listener on it. In the onClickListener, you could add logic to hide the keyboard.

The code below was obtained from this answer

// Catch event on [x] button inside search view
int searchCloseButtonId = searchView.getContext().getResources()
                .getIdentifier("android:id/search_close_btn", null, null);
ImageView closeButton = (ImageView) this.searchView.findViewById(searchCloseButtonId);
// Set on click listener
closeButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       // Manage this event.
    }
});

Inside onClick(View v) you can call a method to hide the keyboard like this

private void hideKeyboard(){
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Community
  • 1
  • 1
11m0
  • 216
  • 7
  • 16