Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android SearchManager 完整解析:把浮動搜索框接進你的 App

編輯:Android 開發實例

SearchManager 的難點不在寫程式,而在配置瑣碎。它橫跨 res/xml、manifest、Java 三個地方,任何一處漏掉都會導致搜索框不出來。這篇文章把整條設定鏈條依序攤開,並補上最常被忽略的單例問題。

步驟一:撰寫 searchable.xml

先在 res/xml/ 下新增設定檔,決定搜索框的標籤、提示文字、是否啟用語音搜索與搜索建議:

<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/search_label"
    android:hint="@string/search_hint"
    android:searchMode="showSearchLabelAsBadge"

    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
    android:voiceLanguageModel="free_form"
    android:voicePromptText="@string/search_invoke"

    android:searchSuggestAuthority="com.android.cbin.SearchSuggestionSampleProvider"
    android:searchSuggestSelection=" ? " />

幾個容易踩雷的欄位:label 顯示在搜索框上方,hint 顯示在框內。searchSuggestAuthority 必須是繼承自 SearchRecentSuggestionsProvider 的完整類別路徑,寫錯時建議功能會靜默失效,不會報錯。

步驟二:在 manifest 宣告結果頁

搜索結果有兩種承載方式:獨立 Activity,或由發起搜索的 Activity 自己處理。先看獨立 Activity 的寫法:

<activity android:name="SearchResultActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
               android:resource="@xml/searchable" />
</activity>

接著在「啟動 Activity」的 <activity> 節點內加上預設搜索目標,這樣每個頁面都能共用同一個搜索框:

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

步驟三:註冊建議 Provider

<provider android:name="SearchSuggestionSampleProvider"
          android:authorities="com.android.cbin.SearchSuggestionSampleProvider">
</provider>

這裡的 authorities 與 searchable.xml 中的 searchSuggestAuthority 指向同一個類,兩邊必須完全一致。

步驟四:觸發搜索框

浮動搜索框不會自己跳出來,需要由按鈕或選單點擊觸發 startSearch():

@Override
public boolean onSearchRequested() {
    String text = etdata.getText().toString();
    Bundle bundle = new Bundle();
    bundle.putString("data", text);

    // 第一個參數:預填到搜索框的初始字串
    // 第三個參數:隨搜索一起傳遞的附加資料
    startSearch("mm", false, bundle, false);
    return true; // 一定要回傳 true
}

回傳值是最常見的錯誤來源。若只呼叫 super.onSearchRequested(),預設文字不會帶入搜索框,Bundle 也傳不出去。

步驟五:接收 query 與 Bundle

public void doSearchQuery() {
    final Intent intent = getIntent();

    String query = intent.getStringExtra(SearchManager.QUERY);
    tvquery.setText(query);

    // 把這次的關鍵字寫入搜尋歷史
    SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
            this,
            SearchSuggestionSampleProvider.AUTHORITY,
            SearchSuggestionSampleProvider.MODE);
    suggestions.saveRecentQuery(query, null);

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        Bundle bundled = intent.getBundleExtra(SearchManager.APP_DATA);
        if (bundled != null) {
            tvdata.setText(bundled.getString("data"));
        } else {
            tvdata.setText("no data");
        }
    }
}

進階:讓搜索框與結果頁共用同一個 Activity

如果發起搜索的頁面本身就是結果頁,預設行為會導致每搜一次就開一個新實例,按返回鍵時疊出一長串相同頁面。解法只有兩步:

第一,在該 Activity 的 manifest 節點加上 android:launchMode="singleTop"。

第二,改寫 onNewIntent(),把原本的接收邏輯搬進來:

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    String query = intent.getStringExtra(SearchManager.QUERY);
    tvquery.setText(query);

    SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
            this,
            SearchSuggestionSampleProvider.AUTHORITY,
            SearchSuggestionSampleProvider.MODE);
    suggestions.saveRecentQuery(query, null);

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        Bundle bundled = intent.getBundleExtra(SearchManager.APP_DATA);
        tvdata.setText(bundled != null ? bundled.getString("data") : "no data");
    }
}

順帶一提:這裡的接收邏輯與 doSearchQuery() 幾乎相同,實務上應該抽成一個共用方法,避免兩處各自演化。

附錄:清空搜尋歷史

private void clearSearchHistory() {
    SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
            this,
            SearchSuggestionSampleProvider.AUTHORITY,
            SearchSuggestionSampleProvider.MODE);
    suggestions.clearHistory();
}

與其提供逐筆刪除,不如在設定頁放一個「清除搜尋紀錄」按鈕,呼叫一次 clearHistory() 即可。

原文出處:https://www.cnblogs.com/jico/archive/2010/11/05/1869814.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved