如何检测SearchView的后退按钮按下? [英] How to detect SearchView's back button press?
问题描述
我正在使用一个活动来显示SearchView以及显示搜索结果.搜索结果只是项目的子集,因此搜索充当过滤器.一切似乎都正常,除了单击SearchView的后退按钮时我不知道如何还原视图中的所有项目.
I'm using a single activity to display SearchView as well as to display search results. The search results is just a subset of items so the search acts as a filter. Everything seems to work fine except that I can't figure out how to restore all items in the view when a back button of SearchView is clicked on.
或者也许还有另一种方法来检测用户何时从搜索结果导航到上一个视图(在我的情况下,该视图是同一视图).
Or maybe there is another way to detect when a user navigates from search results to the previous view (which, in my case, is the same view).
谢谢
推荐答案
因此,看着您的问题的标题,您不确定如何检测SearchView
何时关闭,因此您无法当SearchView
不再打开时,将视图恢复为正常"状态.
So looking at the title of your question, you're not sure how to detect when the SearchView
is being closed and hence you're not able to restore your views to the "normal" state when the SearchView
is not open anymore.
自Android 4.0+起已过时的解决方案
(简单)解决方案是将SearchView.OnCloseListener
添加到您的SearchView
中,如下所示:
The (simple) solution is to add a: SearchView.OnCloseListener
to your SearchView
, like this:
SearchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
// This is where you can be notified when the `SearchView` is closed
// and change your views you see fit.
}
});
编辑:
已更新的解决方案可以在Android 4.0+中运行
显然,OnCloseListener
是有问题的,不能在较新版本的Android(4.0+)上运行.请参阅: https://code.google.com/p/android/issues/detail?id = 25758
Apparently the OnCloseListener
is buggy and doesn't work on newer versions of Android (4.0+). See: https://code.google.com/p/android/issues/detail?id=25758
解决方案是使用SearchView
的支持库版本:
The solution to this is to use the Support library version of the SearchView
:
我的onCreateOptionsMenu
看起来像这样:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchMenuItem = menu.findItem(R.id.searchView);
SearchView searchView = (SearchView) searchMenuItem.getActionView();
MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(ScrollingActivity.this, "onMenuItemActionExpand called", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(ScrollingActivity.this, "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();
return true;
}
});
}
关于Google为什么不费心在我不知道的文档中发表评论,但这很可悲.
As to why Google didn't even bothered to write a comment in the documentation I don't know, but it's sad.
EDIT2 :
只需添加@MateiRadu在评论中添加的链接:
Just adding the link which @MateiRadu added in the comments:
这也显示了如何使用OnActionExpandListener
代替OnCloseListener
.
This also shows how to use the OnActionExpandListener
instead of the OnCloseListener
.
希望这会有所帮助.
这篇关于如何检测SearchView的后退按钮按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!