我为解决类似问题所做的是创建了一个扩展 SearchView 的新类:
public class EnglishVerbSearchView extends SearchView {
OnSearchViewCollapsedEventListener mSearchViewCollapsedEventListener;
public EnglishVerbSearchView(Context context) {
super(context);
}
@Override
public void onActionViewCollapsed() {
if (mSearchViewCollapsedEventListener != null)
mSearchViewCollapsedEventListener.onSearchViewCollapsed();
super.onActionViewCollapsed();
}
public interface OnSearchViewCollapsedEventListener{
public void onSearchViewCollapsed();
}
public void setOnSearchViewCollapsedEventListener(OnSearchViewCollapsedEventListener eventListener) {
mSearchViewCollapsedEventListener = eventListener;
}
}
然后,您可以在菜单 xml 文件中使用此类而不是 SearchView:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="com.szymontrapp.englishverbs.EnglishVerbSearchView" />
</menu>
然后你可以在你的活动中添加一个监听器:
getMenuInflater().inflate(R.menu.dictionary, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
EnglishVerbSearchView searchView = (EnglishVerbSearchView) MenuItemCompat.getActionView(searchItem);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnSearchViewCollapsedEventListener(listener);
您还可以覆盖类中替换 SearchView 的其他方法以实现其他目标。