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
接口有四個可選方法。
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; }
獲取偏好控制器
返回與此片段關聯的首選項控制器列表。此列表用於形成內聯結果、更新不可索引的內容等。
因此,您希望在搜索中顯示的所有內容都必須包含在getXmlResourcesToIndex
或getRawDataToIndex
中。
為您的設置添加關鍵字
為確保設置易於搜索,請添加與用戶可用於搜索設置的設置相關的關鍵字。
添加關鍵字時要考慮的事項:
- 關鍵字是用戶不一定會看到的單詞列表,但可能是他們關於設置如何工作的心理模型的一部分。
- 這些是用戶可能鍵入以進入您的設置的字詞。
- 它們可以是同義詞,也可以使用與設置相關的任何詞。
- 例如,“靜音”可用於查找音量設置。
避免重複
如果您無條件地禁止設置頁面,請刪除原始頁面的索引以避免重複結果。
- 找到您要抑制的頁面的
PreferenceFragment
。 - 刪除
SearchIndexProvider
。
驗證
要測試新設置的可搜索性:
- 在設備上安裝最新版本的 O。
- 通過選擇重新索引數據庫: 設置 > 應用和通知 > 應用信息 > 設置 > 存儲 >清除數據
- 驗證目標設置是否顯示在搜索中。
搜索設置標題的前綴將匹配它。
可以運行這些 robolectric 測試來驗證此功能的實現:
packages/apps/Settings/tests/robotests/src/com/android/settings/search
構建目標是: RunSettingsRoboTests