我也是按照android 文档做的。
在res/xml下 新建searchable.xml
<?xml version="1.0" encoding="utf-8"?> <searchable android:label="@string/app_name" android:hint="@string/search_hint" android:searchSuggestAuthority="com.mengqi.base.provider" android:searchSuggestPath="newsearch" android:searchSuggestSelection="word LIKE ?" android:searchSuggestIntentAction="android.intent.action.VIEW" android:voiceSearchMode="showVoiceSearchButton|launchRecognizer" android:searchSuggestThreshold="2" android:includeInGlobalSearch="true" xmlns:android="http://schemas.android.com/apk/res/android" />
然后在androidManifest.xml定义activity
<activity android:name=".SearchActivity" android:launchMode="singleTop" > <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity>
@Override public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) { getSupportMenuInflater().inflate(R.menu.search, menu); SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(this); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); return super.onCreateOptionsMenu(menu); } @Override public boolean onQueryTextSubmit(String str) { // TODO Auto-generated method stub LogUnit.Log(TAG, "search submit:" + str); return false;//必须返回false 要不然SearchView认为你处理该提交。他不会再进行处理 } @Override public boolean onQueryTextChange(String str) { // TODO Auto-generated method stub LogUnit.Log(TAG, "text change:" + str); return false; }
res/menu 下面新建 search.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:icon="@drawable/ic_action_search" android:id="@id/menu_search" android:orderInCategory="10" android:title="@string/search" android:actionViewClass="com.actionbarsherlock.widget.SearchView" android:showAsAction="ifRoom|collapseActionView" /> </menu>
研究才发现在TestActivity中
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));设置进去的SearchableInfo是空的。
我就新建一个
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));这样子就能够正常运行了。
但是实例都没有这样。为什么就是我的
searchManager.getSearchableInfo(getComponentName())得到的是空值。所以认真寻找 才发现在
androidManifest.xml中还有定义
<meta-data android:name="android.app.default_searchable" android:value=".SearchActivity" />这样子,
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));才能够正常起作用。