0
我想在我的工具欄中實現SearchView,但是當我鍵入內容並確認搜索時,它不會打開結果的活動。在工具欄中實現SearchView
搜索出現在MainActivity中,當用戶輸入某些內容並按下搜索按鈕時,它應該打開SearchResultAcivity。但它不開放。
這裏是我做了什麼:
AndroidManifest:
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SearchResultsActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
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="search" >
</searchable>
菜單項:
<item
android:id="@+id/action_search"
android:title="Search"
android:orderInCategory="100"
android:icon="@drawable/search"
app:actionViewClass = "android.support.v7.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom" />
和:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true); // Iconify the widget
return true;
}