Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 搜索框架完整解析:設定、Activity 與語音搜索

編輯:關於 Android 程式設計

Android 搜索框架概述

Android 內建搜索框架可以協助開發者管理搜索對話框的生命週期。開發者不需要自行設計搜索框位置,也不需要處理它與目前畫面的互動,這些都可以交由 SearchManager 負責。

當使用者執行搜索時,系統會透過特定的 Intent 把關鍵字傳給負責處理搜索結果的 Activity。整體需要準備:

  • 一個搜索設定檔。
  • 一個可處理搜索請求的 Activity。
  • 一個讓使用者開啟搜索框的入口。

建立 searchable.xml

搜索設定檔通常命名為 searchable.xml,並放在 res/xml/ 目錄。

<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/searchLabel"
    android:hint="@string/searchHint" />

其中 android:label 是必要屬性,通常對應應用程式名稱;android:hint 則是輸入提示文字,建議一定要設定。

建立可搜索的 Activity

負責處理搜索的 Activity 需要在 AndroidManifest.xml 中宣告,並加入 intent-filter 與 meta-data。

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

若希望整個 App 都能使用同一個搜索 Activity,可以在 application 層級加入:

<meta-data
    android:name="android.app.default_searchable"
    android:value=".MySearchableActivity" />

接收搜索關鍵字

當搜索對話框送出請求後,Activity 會收到 ACTION_SEARCH Intent,可以從中取出查詢字串。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

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

呼叫搜索對話框

可以透過 onSearchRequested() 開啟搜索框,例如在選單或按鈕中觸發。

@Override
public boolean onSearchRequested() {
    return super.onSearchRequested();
}

若希望使用者按下實體鍵盤按鍵時自動開啟搜索,可以在 onCreate 中設定:

setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

單一 Activity 的搜索處理

若搜索 Activity 設定為 singleTop,新的搜索 Intent 會透過 onNewIntent 傳入,而不是重新建立 Activity。

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(query);
    }
}

加入語音搜索

只要修改搜索設定檔,就能啟用語音搜索按鈕。

<searchable xmlns:android="https://schemas.android.com/apk/res/android"
    android:label="@string/searchLabel"
    android:hint="@string/searchHint"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer" />

透過 Android 原生搜索框架,開發者可以快速建立一致的搜索體驗,也能在需要時擴充語音輸入與搜索建議。

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