At the moment i’m working on an App with a search function. This alone is nothing special. Every second App has a search function. As a standard component the Android SDK offers the class SearchView. You can add an SearchView.OnQueryTextListener to it.
The App has a function that gets called when the user presses the search button on the keyboard and there is no text in the SearchView. But this is not possible with the standard SearchView.
onQueryTextSubmit() gets not called when the query is empty. A look in the source code tells us why:
The listener gets called in onSubmitQuery() of SearchView, but the if-statement checks before if the query length is longer than zero.
When you take a look which methods call onSubmitQuery() you can see that it gets called inside an OnEditorActionListener.
And this listener is added to the SearchAutoComplete class:
SearchAutoComplete informs SearchView with this listener about the key press. Unfortunately SearchView doesn’t offer a possibility to replace SearchAutoComplete with an custom implementation. But let’s take a look in the constructor of SearchView to see how SearchAutoComplete gets created:
SearchView is nothing more than an extended LinearLayout. With findViewById the SearchAutoComplete inside the layout gets inflated. So it should be possible to also inflate the layout to get at the SearchAutoComplete.
I created a class that extends SearchView. Then i’ve overridden the setOnQueryTextListener() method. Since the listener already has the methods i need and I don’t have to make special changes to my existing code.
The listener gets passed to the original SearchView, but in this method I also set a listener to the SearchAutoComplete as explained above. Now every time the user clicks the search button I get the query from the SearchView and pass it to the listener. Except that onQueryTextSubmit() will also get called when the query is empty.