編輯:關於 Android 程式設計
所謂搜索 suggestions(搜索建議、搜索聯想),就是當用戶在搜索框裡輸入某個關鍵詞後,系統自動給出幾條包含相近關鍵詞的候選項,用戶可以直接點擊而不必輸完。
這個功能在 Android 裡有現成的解決方案,核心是 SearchRecentSuggestions 加 SearchRecentSuggestionsProvider 這對組合,不需要自己建數據庫表。

package zhangphil.search;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button search = (Button) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 發起搜索
search();
}
});
Button clear = (Button) findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clear();
}
});
}
private void search() {
// 向 Android 系統發起搜索請求
this.onSearchRequested();
}
/**
* onSearchRequested() 方法可以重載,也可以不重載,
* 取決於是否需要傳遞更多參數或數據給下一步操作。
* 通常代碼運行邏輯需要傳遞更多數據時,則重載此方法以完成更多數據的傳遞;
* 不重載也可以,系統會啟動默認的搜索框。
*/
@Override
public boolean onSearchRequested() {
Bundle bundle = new Bundle();
bundle.putString("some_key", "some_value");
this.startSearch("輸入搜索的關鍵詞" /* 初始化搜索框中的提示詞 */,
true,
bundle,
false /* 此處若為 true,則啟動手機全局設置的搜索,比如 Google 搜索 */);
return true;
}
// 清除全部歷史搜索記錄
private void clear() {
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
ZhangPhilSuggestionProvider.AUTHORITY,
ZhangPhilSuggestionProvider.MODE);
// 出於用戶隱私的考慮,給 APP 提供清除所有搜索歷史記錄的選項
suggestions.clearHistory();
}
}
onSearchRequested() 會觸發 Android 系統自動彈出搜索框,這是系統級組件,外觀與行為都與其他應用的搜索保持一致。
關於 startSearch() 的四個參數值得說明:初始提示詞、是否走應用級搜索、附加的 Bundle 數據、以及是否使用全局搜索。第四個參數傳 true 會調起系統全局搜索(例如 Google 搜索),多數情況下我們傳 false。
activity_main.xml 很簡單,兩個按鈕:一個觸發搜索,一個清除歷史記錄。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/search" />
<Button
android:id="@+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clear" />
</LinearLayout>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="zhangphil.search"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- 指定默認的 searchable Activity -->
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchActivity" />
</activity>
<activity android:name=".SearchActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- 關聯 searchable 配置 -->
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<!-- 註冊 suggestions 提供者 -->
<provider
android:name=".ZhangPhilSuggestionProvider"
android:authorities="ZhangPhil_AUTHORITY" />
</application>
</manifest>
這裡有三處配置缺一不可:default_searchable 指明誰來處理搜索意圖,searchable 關聯搜索策略配置文件,<provider> 註冊建議數據的 ContentProvider。
package zhangphil.search;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.widget.Toast;
public class SearchActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// 保存關鍵詞
saveMyRecentQuery(intent);
}
}
private void saveMyRecentQuery(Intent intent) {
// 把搜索的關鍵詞保存到 Android 系統自帶的數據庫中
// 如無必要定制,此過程可以使用標准、通用的方法
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
ZhangPhilSuggestionProvider.AUTHORITY,
ZhangPhilSuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
Toast.makeText(this, "搜索關鍵詞:" + query, Toast.LENGTH_LONG).show();
}
}
關鍵是判斷 Intent.ACTION_SEARCH,然後通過 SearchManager.QUERY 取出用戶輸入的關鍵詞,交給 saveRecentQuery() 落庫。saveRecentQuery() 的第二個參數是 String selectionLine,一般傳 null,只有在需要「第二行說明文字」時才使用。
package zhangphil.search;
import android.content.SearchRecentSuggestionsProvider;
public class ZhangPhilSuggestionProvider extends SearchRecentSuggestionsProvider {
// 可隨意定義一個可區別的字符串,但注意全局的唯一相同引用
public final static String AUTHORITY = "ZhangPhil_AUTHORITY";
public final static int MODE = DATABASE_MODE_QUERIES;
public ZhangPhilSuggestionProvider() {
setupSuggestions(AUTHORITY, MODE);
}
}
整個 Provider 就這麼幾行——SearchRecentSuggestionsProvider 已經把 SQLite 建表、增刪查改、以及供搜索框查詢的 query() 方法全部實現好了,我們只需要在構造函數裡調用 setupSuggestions() 完成初始化。
MODE 的可選值有幾種:DATABASE_MODE_QUERIES 只存關鍵詞(最常用),DATABASE_MODE_QUERIES_SHORTCUTS 則支持為每條記錄配置二行文本/shortcut,適合需要展示副標題的場景。
最後在 res/xml/searchable.xml 中描述搜索行為:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="https://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:searchSuggestAuthority="ZhangPhil_AUTHORITY"
android:searchSuggestIntentAction="android.intent.action.VIEW"
android:searchSuggestSelection=" ?"
android:includeInGlobalSearch="true"
android:searchSettingsDescription="@string/search_setting" />
這裡有兩個屬性特別容易寫錯:
android:searchSuggestSelection:如果 Provider 使用 DATABASE_MODE_QUERIES 模式,這裡必須填空字符串;如果填 " ?" 反而是用於自定義 Provider 的場景。兩者對應關係寫反會導致點擊建議項時搜索不到結果。android:includeInGlobalSearch:設為 true 表示本應用的搜索建議要參與系統全局搜索。此時必須在清單文件中為 provider 加上 android:searchSettingsDescription 描述的字符串資源,否則安裝時會報錯。如果你的需求是「基於服務器數據的聯想」而非「基於歷史記錄的聯想」,那就不該用 SearchRecentSuggestions,而要自定義 ContentProvider 並在 query() 裡返回 SearchManager.SUGGEST_COLUMN_TEXT_1 等列——這兩種方案的區分,是實際開發中最容易混淆的一點。
百行 Android 程式碼,手寫一個會長高的動畫柱狀圖
做專案的時候碰到一個需求:頁面上要放幾根柱子來展示數據。看似簡單,但仔細一想,柱子的頂端要帶圓角,上方還要浮著數值,最關鍵的是——進場時柱子得一根根「長」起來。單純用 D
微信被舉報怎麼辦?6 個實用的微信解封方法
微信運營過程中難免遇到意外,比如在朋友圈被惡評,甚至被別有用心的人惡意舉報,這些煩心事著實令人頭疼。平日裡常聽人說做人要低調,正是為了避免不必要的麻煩。那麼萬一微信真的被
Android 圖像級別資源 level-list 使用教學
在 Android 中,若想根據不同狀態切換圖片,除了使用 selector 狀態資源,也可以使用圖像級別資源,也就是 level-list。它允許開發者定義多個級別區間
Android 屏幕適配完全指南:基礎概念、布局、圖片與代碼四個層面
讓同一個界面在不同尺寸、不同分辨率的手機上呈現一致的效果,是每個 Android 開發者繞不開的功課。本文把常見做法梳理成四塊:先講清基礎概念,再分別從布局、圖片和代碼三