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

Android 開發深入淺出:搜尋框架實作(二)加入搜尋歷史提示

編輯:Android 開發實例

接續上一篇,本文要說明如何在搜尋時彈出「搜尋歷史提示」,讓使用者能快速重複過去的搜尋。

一、建立搜尋建議提供者

好消息是,Android 已經為我們準備好了一個預設的實作,我們只需繼承 SearchRecentSuggestionProvider 並稍作修改即可。

import android.content.SearchRecentSuggestionsProvider;

/**
 * 搜索提示
 */
public class SearchSuggestionsProvider extends SearchRecentSuggestionsProvider {
    // 記住這個
    public final static String AUTHORITY = "searchprovider";

    public final static int MODE = DATABASE_MODE_QUERIES;

    public SearchSuggestionsProvider() {
        setupSuggestions(AUTHORITY, MODE);
    }
}

這裡有兩個關鍵常數:AUTHORITY 是這個 Suggest Provider 的授權名稱,後續會在設定檔中引用;MODE 設為 DATABASE_MODE_QUERIES,表示以查詢紀錄模式運作。建構子中呼叫 setupSuggestions,把這兩者綁定起來。

二、配置 searchable.xml

接著在 res/xml 目錄下建立 searchable.xml,宣告搜尋相關設定:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/search_label"
    android:hint="@string/search_hint"
    android:searchSettingsDescription="@string/search_settings_description"
    android:searchSuggestAuthority="searchprovider"
    android:searchSuggestIntentAction="android.intent.action.SEARCH"
    android:searchSuggestThreshold="1"
    android:includeInGlobalSearch="true"
    android:searchSuggestSelection=" ?"
>
</searchable>

參數說明:

android:searchSuggestAuthority:此屬性的值就是 Provider 中的 AUTHORITY。

android:searchSuggestIntentAction:定義當我們選中某個搜尋提示內容時要觸發的意圖動作。

android:searchSuggestThreshold:定義至少輸入幾個字元時才會彈出提示(此處設為 1)。

android:includeInGlobalSearch:是否將內容加入 Android 的全域搜尋,設為 true 即加入。

android:searchSuggestSelection:定義搜尋時參數的佔位符。

以上僅是部分參數,更多設定可以自行參考 Android 官方手冊。

三、配置 AndroidManifest.xml

最後,別忘了在 AndroidManifest.xml 中註冊這個 Provider:

<provider android:name=".SearchSuggestionsProvider"
    android:authorities="searchprovider" />

要特別注意 authorities 屬性的值必須與前面 AUTHORITY 常數保持一致,否則系統將無法正確關聯到這個建議提供者。

完成這三個步驟後,每當使用者進行搜尋,系統就會記錄查詢歷史,並在下次輸入時自動彈出相關的搜尋提示,大幅提升操作的便利性。

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