編輯: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,把這兩者綁定起來。
接著在 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 中註冊這個 Provider:
<provider android:name=".SearchSuggestionsProvider"
android:authorities="searchprovider" />
要特別注意 authorities 屬性的值必須與前面 AUTHORITY 常數保持一致,否則系統將無法正確關聯到這個建議提供者。
完成這三個步驟後,每當使用者進行搜尋,系統就會記錄查詢歷史,並在下次輸入時自動彈出相關的搜尋提示,大幅提升操作的便利性。
Android 本地化:讓應用程式適配不同語言環境
Android 應用程式可以在許多不同地區的許多裝置上執行。為了讓應用程式更具互動性,它應該能處理文字、數字、檔案等內容,使其適配應用程式即將使用的語言環境。 本章將說明
Android 彈出視窗的兩種做法:PopupWindow 與 Activity 偽窗口
目前見過的彈出視窗實作主要有兩種:最常見的 PopupWindow,以及用 Activity 假裝成彈窗的寫法。後者看起來相當有創意——沒想到 Activity 也能拿來
Eclipse 中 aapt.exe 停止工作的排查方式
問題現象 在 Eclipse 開發 Android 專案時,若版面配置或 XML 檔有錯誤,可能會突然出現 aapt.exe 停止工作的提示。這類錯誤不一定伴隨明確訊息,
Android MediaPlayer 範例:播放、暫停與快轉
範例功能這個範例會示範如何使用 MediaPlayer 建立一個簡單的音訊播放器,包含播放、暫停、快轉與倒轉功能。建立 MediaPlayer將音訊檔放在 raw 資料夾