2016-02-10 44 views
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; 
} 

回答

1

在你的清單中你犯了一個錯誤。

我假設你想在所有activitys搜索和工作,你需要mainactivity之前把這個:

<meta-data 
     android:name="android.app.default_searchable" 
     android:value="yourpakagename.yourresultactivity" /> 

,並把這個內部searchresultactivity:

<meta-data 
    android:name="android.app.searchable" 
    android:resource="@xml/searchable" /> 

的結果是這樣的:

<meta-data 
     android:name="android.app.default_searchable" 
     android:value="yorpakagename.yourresultactivity" /> 

    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

<activity android:name=".searchableactivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.SEARCH" /> 
     </intent-filter> 

     <meta-data 
      android:name="android.app.searchable" 
      android:resource="@xml/searchable" /> 
    </activity> 
相關問題