我想扩展SearchView类以覆盖onKeyDown()方法。所以我在我的片段类中进行如下操作:
public class myfragment extends ListFragment{
...
class CustomSearchView extends SearchView{
public CustomSearchView(Context context) {
super(context);
}
public CustomSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
Toast.makeText(getActivity(), "onkeydown", Toast.LENGTH_SHORT).show();
return super.onKeyDown(keyCode, event);
}
}
...
}
现在我想在片段中使用这个扩展的SearchView。但我不知道该怎么做。由于我使用searchItem.getActionView()创建了SearchView对象,有什么方法可以将它转换为CustomSearchView对象,以便在我的片段中触发重写的onKeyDown方法?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
...
// Retrieves the system search manager service
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
// Retrieves the SearchView from the search menu item
final SearchView searchView = (SearchView) searchItem.getActionView();
// Assign searchable info to SearchView
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String queryText) {
// Nothing needs to happen when the user submits the search string
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
...
}
});
由于How can I get onBackPressed() while SearchView is activated?
中提到的解决方案,此问题突然出现答案 0 :(得分:0)
您可以转换为自定义SearchView
:
final CustomSearchView searchView = (CustomSearchView) searchItem.getActionView();
当您声明SearchView
时,您必须在meny xml文件中使用完整的类名声明自己的SearchView。此外,如果您使用支持库,则必须声明http://schemas.android.com/apk/res-auto
命名空间:
没有支持库:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/action_search"
android:showAsAction="always|collapseActionView"
android:actionViewClass="com.xxx.ListFragment.CustomSearchView" />
支持库:
<?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="always|collapseActionView"
yourapp:actionViewClass="com.xxx.ListFragment.CustomSearchView" />