我尝试在操作栏中制作 SearchView 以启动一个 SearchResultsActivity,该活动已注册以处理 ACTION_SEARCH。我做了所有必需的步骤,但仍然没有工作!
这是代码:
1.搜索查看菜单项:(menu/main.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/search_action" android:icon="@android:drawable/ic_menu_search" android:actionViewClass="android.widget.SearchView" android:showAsAction="always|collapseActionView" /> </menu>
2.可搜索配置(xml/searchable.xml):
<?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/app_name" android:hint="@string/search_hint"/>
2.1 AndroidManifest.xml中MainActivity添加Searchable配置链接:
<activity android:name="com.me.searchonpre3.MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity>
3. 将搜索视图菜单项与搜索配置(MainActivity.java)绑定:
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ SearchView searchView = (SearchView) menu.findItem(R.id.search_action).getActionView(); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); if (searchView != null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } } return true; }
4.添加新的Activity“SearchResultsActivity”并将其标记为处理SEARCH_ACTIONs:
公共类 SearchResultsActivity 扩展 ListActivity {
public static final String TAG = SearchResultsActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "In SearchResult OnCreate"); setContentView(R.layout.activity_search_results); this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[]{"Product1", "Product2"})); } }
AndroidMainfest.xml:
<activity
android:name="com.me.searchonpre3.SearchResultsActivity"
android:label="@string/title_activity_search_results">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
</activity>
上述所有设置和 SearchResultsActivity 在按下 Search 键盘图标时不会启动。
我还应该做什么???
注意:当我添加 setOnQueryTextListener 时,会在 MainActivity 类上调用回调。