我按照
Android API Guide中的描述设置了一个SearchWidget.它在Action Bar中正确显示一个放大镜图标,如果我点击它,它会在Action Bar(一个深色背景的输入字段)中启动搜索小部件.
但是,如果我按下虚拟设备的搜索按钮,则会启动另一个搜索字段:它具有白色背景,并且不会调用我指定的回调方法.
所以我把它添加到我的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().”