[英]Query in a SearchView is lost after closing and opening it again
I'm working on a Fragment in which I have a SearchView. 我正在研究其中有SearchView的Fragment。 If I close the SearchView and then reopen it, the query I typed is gone.
如果我关闭SearchView然后重新打开它,那么我键入的查询就消失了。
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.
我想要类似Google Play商店中SearchView的行为,如果我关闭并打开它,查询仍然存在。
May it have something to do with the fact that I don't have a searchable.xml? 这可能与我没有searchable.xml的事实有关吗?
You need to create an onCloseListener according to the documentation: 您需要根据文档创建一个onCloseListener:
Returns true if the listener wants to override the default behavior of clearing the text field and dismissing it, false otherwise.
如果侦听器想要覆盖清除文本字段并将其关闭的默认行为,则返回true,否则返回false。
See http://developer.android.com/reference/android/widget/SearchView.OnCloseListener.html#onClose() 参见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. 我不确定在查看SearchView的源代码(如果查询TextView为空时似乎仅调用onCloseListener)后是否能正常工作。
Check out SearchView.onCloseClicked() to see what is happening: 查看SearchView.onCloseClicked()以查看发生了什么:
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. 因此,如果覆盖onCloseListener不起作用,这就是原因。
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. 由于SearchView是公共的,因此您可以扩展该类并修复onCloseClicked()的逻辑,或者重写onActionViewExpanded / onActionViewCollapsed以恢复和保存查询字符串。
You could also try saving the query in your OnQueryTextListener and then calling setQuery(savedQuery, false) in onOptionsItemSelected. 您也可以尝试将查询保存在OnQueryTextListener中,然后在onOptionsItemSelected中调用setQuery(savedQuery,false)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.