Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close listener of searchview in layout is not working Android

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;
        }
    });
like image 550
shivani gupta Avatar asked Feb 20 '17 06:02

shivani gupta


1 Answers

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);
}
like image 63
11m0 Avatar answered Sep 28 '22 07:09

11m0