萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 系統搜尋框整合搜尋建議與歷史記錄:SearchRecentSuggestionsProvider 完整實作

架構概覽

  • searchable.xml:定義搜尋提示、建議授權單位。
  • Manifest:註冊 <meta-data android:name="android.app.searchable"> 與 <provider>。
  • SearchRecentSuggestionsProvider:內建 SQLite 儲存歷史查詢。
  • Activity:處理 ACTION_SEARCH Intent 並儲存查詢。

1. 定義 searchable.xml (res/xml/searchable.xml)

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

2. Manifest 片段

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

<provider
    android:name=".SearchSuggestionProvider"
    android:authorities="com.example.SearchSuggestionProvider" />

3. Provider 實作

public class SearchSuggestionProvider extends SearchRecentSuggestionsProvider {
    public static final String AUTHORITY = "com.example.SearchSuggestionProvider";
    public static final int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES;

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

4. Activity 處理搜尋與儲存

public class MainActivity extends Activity {
    @Override public boolean onSearchRequested() {
        startSearch(null, false, null, true); // 啟動系統搜尋框
        return true;
    }

    @Override protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            // 顯示結果邏輯...
            // 儲存歷史
            SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                    SearchSuggestionProvider.AUTHORITY, SearchSuggestionProvider.MODE);
            suggestions.saveRecentQuery(query, null);
        }
    }
}

呼叫搜尋框

// 任意位置
onSearchRequested();
// 或
startSearch(null, false, null, false);

總結

利用系統內建 SearchRecentSuggestionsProvider 免去自建資料庫,幾行程式碼即可擁有搜尋建議與歷史記錄功能。

copyright © 萬盛學電腦網 all rights reserved