1.manifest中声明处理搜索的Activity(仅此声明后就可以调用)
<meta-data android:name="android.app.default_searchable" android:value=".OnSearchAppsList" />
2.Activity定义
<activity android:name=".OnSearchAppsList" android:configChanges="orientation|keyboardHidden|navigation" android:label="@string/Market"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity>
3.searchable.xml定义
<?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/search_label" android:hint="@string/search_hint" />
4.调用 Search功能
onSearchRequested();
5.截获 参数
getIntent().getStringExtra(SearchManager.QUERY);
这后即可以随意处理搜索请求了。
具体使用时可以结合Activity的showDialog方法:
private static final int DIALOG_SEARCH_TEXT = 1;
@Override public boolean onSearchRequested() { showDialog(DIALOG_SEARCH_TEXT); return false; }
@Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SEARCH_TEXT: LayoutInflater factory = LayoutInflater.from(this); final View searchView = factory.inflate(R.layout.dialog_search_article, null); final EditText editText = (EditText)searchView.findViewById(R.id.search_query); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_NULL) { InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow( editText.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); dismissDialog(DIALOG_SEARCH_TEXT); doSearch(editText); return true; } return false; } }); return new AlertDialog.Builder(this) .setTitle(R.string.search_article_title) .setView(searchView) .setPositiveButton(R.string.search_article_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { doSearch(editText); } }) .setNegativeButton(R.string.search_article_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { } }).create(); } return null; }