I'm working on a Fragment in which I have a SearchView. If I close the SearchView and then reopen it, the query I typed is gone.
The problem is I don't want this behavior. I want the behavior like the SearchView in the Google Play store, where the query is still there if I close and open it.
May it have something to do with the fact that I don't have a searchable.xml?
You need to create an onCloseListener according to the documentation:
Returns true if the listener wants to override the default behavior of clearing the text field and dismissing it, false otherwise.
See http://developer.android.com/reference/android/widget/SearchView.OnCloseListener.html#onClose()
I'm uncertain if this works properly after looking at the source code for SearchView which seems to only call the onCloseListener if the query TextView is empty.
Check out SearchView.onCloseClicked() to see what is happening:
private void onCloseClicked() {
CharSequence text = mQueryTextView.getText();
if (TextUtils.isEmpty(text)) {
if (mIconifiedByDefault) {
// If the app doesn't override the close behavior
if (mOnCloseListener == null || !mOnCloseListener.onClose()) {
// hide the keyboard and remove focus
clearFocus();
// collapse the search field
updateViewsVisibility(true);
}
}
} else {
mQueryTextView.setText("");
mQueryTextView.requestFocus();
setImeVisibility(true);
}
}
So if overriding the onCloseListener doesn't work that's why.
Since SearchView is public you can extend the class and fix the logic of onCloseClicked() or override onActionViewExpanded / onActionViewCollapsed to restore and save the query string.
You could also try saving the query in your OnQueryTextListener and then calling setQuery(savedQuery, false) in onOptionsItemSelected.