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

Android 搜尋功能(下):修改 searchable 設定與儲存查詢記錄

編輯:Android 開發實例

接續上一篇建立好 SearchRecentSuggestionsProvider 之後,還有兩件事要做:改寫 searchable 設定檔,以及在使用者每次搜尋時把關鍵字寫入 Provider。

一、修改 searchable 設定

在 res/xml/searchable.xml 的 <searchable> 節點上補兩個屬性,把系統導向你的 suggestion provider:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint"
    android:searchSuggestAuthority="com.example.MySuggestionProvider"
    android:searchSuggestSelection=" ?" />

android:searchSuggestAuthority 必須是 ContentProvider 的完整授權名稱,和 setupSuggestions(AUTHORITY, MODE) 中的 AUTHORITY 完全一致;android:searchSuggestSelection 則固定填「空格加問號」(" ?"),這是 SQLite 查詢的參數佔位符,系統會自動替換成使用者輸入的文字。

二、儲存查詢記錄

要建立「最近搜尋」集合,需要把 searchable activity 收到的每個查詢都交給 SearchRecentSuggestionsProvider。做法是建立一個 SearchRecentSuggestions 物件,並呼叫它的 saveRecentQuery()。以下 示例 3 示範在 onCreate() 中完成這件事:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent = getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);

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

SearchRecentSuggestions 的建構子需要兩個參數,也就是你在 ContentProvider 中設定的搜尋授權與資料庫模式,兩者必須與 Provider 端一致。

saveRecentQuery() 的第一個參數是搜尋關鍵字;第二個參數是選用的,代表該筆建議的「第二行文字」,若沒有第二行就傳 null。只有在資料庫模式加上 DATABASE_MODE_2LINES(two-line mode)時,第二個參數才會生效——啟用後,系統比對建議項目時會同時拿 query text 去匹配這行文字。

三、清空建議資料

為了保護使用者隱私,一定要提供清除最近搜尋記錄的入口,呼叫 clearHistory() 即可:

SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
        HelloSuggestionProvider.AUTHORITY, HelloSuggestionProvider.MODE);
suggestions.clearHistory();

實務上建議掛在「清除搜尋歷史」的選單項或設定頁按鈕上,而且在真正執行清除之前先跳一個確認對話框,讓使用者二次確認是否真的要刪除這些紀錄——畢竟這是不可逆的操作。

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