編輯:Android 開發實例
接續上一篇建立好 SearchRecentSuggestionsProvider 之後,還有兩件事要做:改寫 searchable 設定檔,以及在使用者每次搜尋時把關鍵字寫入 Provider。
在 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();
實務上建議掛在「清除搜尋歷史」的選單項或設定頁按鈕上,而且在真正執行清除之前先跳一個確認對話框,讓使用者二次確認是否真的要刪除這些紀錄——畢竟這是不可逆的操作。
使用 PHP for Android 與 SL4A 打造 Android 應用
PHP for Android 讓開發者能在 Android 上以 PHP 撰寫腳本,搭配 Scripting Layer for Android,也就是 SL4A,可快
打造可橫向又縱向滾動的表格:ListView 固定列頭實作
由於專案需求,我們需要一個既能橫向滾動、又能縱向滾動,還得應付大資料量(多列)的表格視圖。折騰幾天終於搞定,做個示範,先貼圖: 來看看背後的思路: 設計思路 1. 上
Android 登錄實例:建立登入介面並管理錯誤嘗試
登入應用程式的畫面會要求使用者輸入憑證,才能登入某個特定的應用,例如 Facebook、微博等服務。 本章介紹如何建立一個登入介面,以及如何管理安全問題與錯誤嘗試次數。
Android 應用本地化:讓 App 自適應多語系環境
Android App 常在不同語言與地區的裝置上執行。若希望使用者看到符合當地語言的文字,就必須進行本地化。最常見的做法是把字串抽到 strings.xml,再依語言建