Android 8.0 為「設定」選單新增了擴充搜尋功能。本文將說明如何新增設定,並確保設定搜尋功能可正確編入索引。
建立可建立索引的設定
每個需要建立索引的設定片段都會實作 Indexable
介面,且需要靜態欄位:
public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER
設定片段以便進行索引後,請將其新增至位於以下位置的 SearchIndexableResources
:
packages/apps/Settings/src/com/android/settings/search/SearchIndexableResources.java
選用方法
這個 SearchIndexProvider
介面有四個選用方法。
getXmlResourcesToIndex
- 如果片段內容來自以下來源,請覆寫此值:
preference xml
- 傳回 XML 偏好設定做為要建立索引的清單。
XML 資源範例:
public List<SearchIndexableResource> getXmlResourcesToIndex(Context context, boolean enabled) { ArrayList<SearchIndexableResource> result = new ArrayList<SearchIndexableResource>(); SearchIndexableResource sir = new SearchIndexableResource(context); sir.xmlResId = R.xml.display_settings; result.add(sir); return result; }
getRawDataToIndex
- 如果片段內容並非來自
preference xml
,請覆寫此值 - 傳回要建立索引的原始資料 (
SearchIndexableRaw
) 清單。
原始資料範例:
public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { final List<SearchIndexableRaw> result = new ArrayList<>(); final Resources res = context.getResources(); // Add fragment title SearchIndexableRaw data = new SearchIndexableRaw(context); data.title = res.getString(R.string.wifi_settings); data.screenTitle = res.getString(R.string.wifi_settings); data.keywords = res.getString(R.string.keywords_wifi); data.key = DATA_KEY_REFERENCE; result.add(data); return result; }
getNonIndexableKeys
- 如果片段是
DashboardFragment
,您幾乎不需要覆寫這個值。 - 傳回對應於特定使用者、裝置、設定等的結果的鍵清單。此處提供的鍵應與
SearchIndexableResource
和SearchIndexableRaw
中的 KEY 欄位相符。 - 舉例來說:如果使用者從未在裝置中插入 SIM 卡,則不應顯示「數據用量」。
無法建立索引的鍵示例:
public List<String> getNonIndexableKeys(Context context) { final List<String> keys = super.getNonIndexableKeys(context); if (!checkIntentAction(context, "android.settings.TERMS")) { keys.add(KEY_TERMS); } if (!checkIntentAction(context, "android.settings.LICENSE")) { keys.add(KEY_LICENSE); } if (!checkIntentAction(context, "android.settings.COPYRIGHT")) { keys.add(KEY_COPYRIGHT); } if (!checkIntentAction(context, "android.settings.WEBVIEW_LICENSE")) { keys.add(KEY_WEBVIEW_LICENSE); } return keys; }
getPreferenceControllers
傳回與此片段相關聯的偏好設定控制器清單。這份清單可用於建立內嵌結果、更新無法索引的項目等。
因此,您想在搜尋結果中顯示的所有內容都必須包含在 getXmlResourcesToIndex
或 getRawDataToIndex
中。
為設定加入關鍵字
為確保設定容易搜尋,請加入與設定相關的關鍵字,方便使用者搜尋設定。
新增關鍵字時的注意事項:
- 關鍵字是使用者不一定會看到的字詞清單,但可能會是他們對設定運作方式的認知模型的一部分。
- 這些是使用者可能輸入的字詞,以便前往您的設定。
- 這些字詞可以是同義詞,也可以是與設定相關的任何字詞。
- 舉例來說,你可以使用「靜音」來尋找音量設定。
避免重複
如果要無條件抑制設定頁面,請移除原始網頁的索引,以免產生重複的結果。
- 找出要停用的網頁的
PreferenceFragment
。 - 移除
SearchIndexProvider
。
驗證
如要測試新設定的可搜尋性:
- 在裝置上安裝最新版 O。
- 如要重新建立資料庫索引,請選取下列項目: 依序前往「設定」>「應用程式與通知」>「應用程式資訊」>「設定」>「儲存空間」>「清除資料」
- 確認目標設定會顯示在搜尋結果中。
搜尋設定名稱的前置字串,系統就會比對。
您可以執行下列 Robolectric 測試,驗證此功能的實作方式:
packages/apps/Settings/tests/robotests/src/com/android/settings/search
建構目標為:RunSettingsRoboTests