但是,如果我按下虚拟设备的搜索按钮,则会启动另一个搜索字段:它具有白色背景,并且不会调用我指定的回调方法.
所以我把它添加到我的MainActivity类:
public boolean onSearchRequested() { SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setIconified(!searchView.isIconified()); return false; }
搜索小部件的设置与文档中描述的完全相同:
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); searchView.setonQueryTextListener(new CustomSearchQueryTextListener());
我的searchable.xml:
<?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/app_name"> </searchable>
和AndroidManifest.xml:
<activity android:name="MainActivity" android:label="@string/app_name" android:launchMode="singleTask" android:uiOptions="splitactionBarWhenNarrow" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <Meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity>
我尝试使用setIconfied()方法的原因是,在Android API指南中,它说“切换搜索框可见性的能力”:
“By default,the search widget is “iconified,” meaning that it is
represented only by a search icon (a magnifying glass),and expands to
show the search Box when the user touches it. As shown above,you can
show the search Box by default,by calling
setIconifiedByDefault(false). You can also toggle the search widget
appearance by calling setIconified().”
我也尝试调用startSearch(“”,false,null,false);但这会带来与白色背景相同的搜索字段.
所以我的问题是:如果用户按下设备的搜索按钮,是否可以在操作栏中启动搜索小部件,即执行与单击搜索菜单项完全相同的操作?
解决方法
您需要做的就是在搜索菜单项上调用expandActionView(),一切都按预期工作:
public boolean onSearchRequested() { menu.findItem(R.id.menu_search).expandActionView(); return true; }