Android 8.0 為「設定」選單新增了擴充的搜尋功能。本文檔介紹如何新增設定並確保為設定搜尋正確索引該設定。
建立可索引設定
每個需要索引的Settings片段都實作了Indexable
接口,並且需要靜態欄位:
public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER
將片段設定為索引後,將其新增至位於下列位置的SearchIndexableResources
:
packages/apps/Settings/src/com/android/settings/search/SearchIndexableResources.java
可選方法
此SearchIndexProvider
介面有四個可選方法。
取得XmlResourcesToIndex
- 如果您的片段內容來自:
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; }
取得原始資料到索引
- 如果您的片段內容不是來自:
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; }
取得不可索引的鍵
- 如果您的片段是
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; }
取得首選項控制器
傳回與此片段關聯的首選項控制器的清單。此列表用於形成內聯結果、更新不可索引的結果等。
因此,您想要在搜尋中顯示的所有內容都必須包含在getXmlResourcesToIndex
或getRawDataToIndex
中。
為您的設定新增關鍵字
為了確保設定易於搜索,請新增與使用者可以用來搜尋該設定的設定相關的關鍵字。
新增關鍵字時需要考慮的事項:
- 關鍵字是用戶不一定會看到的單字列表,但可能是他們關於設定如何運作的心理模型的一部分。
- 使用者可能會鍵入這些單字來存取您的設定。
- 它們可以是同義詞,也可以使用與設定相關的任何單字。
- 例如,「靜音」可用於尋找音量設定。
避免重複
如果您無條件隱藏某個設定頁面,請刪除原始頁面的索引以避免結果重複。
- 找到您要隱藏的頁面的
PreferenceFragment
。 - 刪除
SearchIndexProvider
。
驗證
要測試新設定的可搜尋性:
- 在設備上安裝最新版本的 O。
- 透過選擇以下內容重新索引資料庫: 設定 > 應用程式與通知 > 應用程式資訊 > 設定 > 儲存 >清除數據
- 驗證目標設定是否顯示在搜尋中。
搜尋設定標題的前綴將與其相符。
可以運行這些機器人測試來驗證此功能的實作:
packages/apps/Settings/tests/robotests/src/com/android/settings/search
建構目標是: RunSettingsRoboTests