这就是我使用 ActionBarSherlock 实现搜索的方式:
在res/menu文件夹下的menu.xml中,我添加了一个图标:
<item android:id="@+id/search"
android:title="@string/search_title"
android:icon="@drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"/>
然后,我创建了一个类,负责接收操作搜索查询并呈现数据:
public class SearchActivity extends SherlockFragmentActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "This is the search view activity");
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_result_layout);
}
private void handleIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
searcdhQuery = intent.getStringExtra(SearchManager.QUERY);
//here we shall do e search..
Log.d(TAG, "This is the search query:" + searcdhQuery);
//This is the asynctask query to connect to the database...
String[] value = {searcdhQuery};
SearchQuery searchQuery = new SearchQuery();
searchQuery.execute(value);
}
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
handleIntent(intent);
}
}
在清单中,此活动包含在搜索和查看过滤器中,如下所示:
<activity android:name=".SearchActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
另外,在清单中,不要忘记应用程序中显示活动默认搜索的元数据,如下所示:
<meta-data android:name="android.app.default_searchable"
android:value=".SearchActivity" />
最后在 onCreateOptionsMenu 中,确保通过将搜索配置与搜索服务关联来添加搜索配置:
//associating the searchable configuration with the search service...
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView)menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
onOptionsItemSelected 方法中不需要任何内容。
这对我来说非常有效。如果您需要更多详细信息,请从搜索 查看演示在actionBar中夏洛克和关于设置搜索界面的开发人员教程.
我希望这有帮助。