Search code examples
javaandroidonclicklistenersearchview

How to set x button once to clear text and second to close SearchView Android?


I have this SearchView:

SearchView searchView = findViewById(R.id.search);

Once I write some text and I press the clear button, the text is cleared and if I press again, the search is closed. If use the following lines of code:

ImageView clearButton = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
clearButton.setOnClickListener(v -> {
    searchView.setQuery("", false);
});

The default behaviour stops working. I set on click listener on the button and it works fine but if I press again, the search is not closing as it happened earlier. How to close the search on second button click?


Solution

  • Use setIconified to true to close the SearchView

    clearButton.setOnClickListener(v -> {
        if(searchView.getQuery().length() == 0) {
            searchView.setIconified(true);
        } else {
            searchView.setQuery("", false);
        }
    });