I am trying to use SearchView, and I have everything to work, except when I want to search for an empty string.
OnQueryTextChange reacts when I delete the last character, but I want the user to be able to click the search button when the search field is empty.
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
I also tried using OnKeyListner. but it doesn’t work either.
searchView.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
return true;
}
});
It seems like such a simple thing, but I can't get it to work. Any suggestions?
Edit
I searched for a solution for a while and a few minutes after posting this question I found a solution.
In this thread, I found out that this is not a mistake, but in fact it was intentional.
Android SearchView.OnQueryTextListener OnQueryTextSubmit not starting in empty query string
, ActionBarSherlock onSubmitQuery()
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if (query != null && TextUtils.getTrimmedLength(query) > 0) {
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
setImeVisibility(false);
}
dismissSuggestions();
}
}
}
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if(query == null) {query = "";}
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
setImeVisibility(false);
}
dismissSuggestions();
}
}
, , - .