經過以下幾個部分的實現和配置,Android內建的搜索框架就可以在你的應用中方便使用了。
1 在需要顯示search ui界面的activity中調用search的代碼
-
/** Handle "search" title-bar action. */
-
public void onSearchClick(View v) {
-
onSearchRequested();
-
}
-
-
/** do the search **/
-
@Override
-
public boolean onSearchRequested() {
-
Bundle appDataBundle = new Bundle();
-
appDataBundle.putString("param1", "test");
-
startSearch("請輸入搜索的關鍵詞", true, appDataBundle, false);
-
return true;
-
}
複製代碼
2 創建xml/searchable.xml 對search的配置
-
<?xml version="1.0" encoding="utf-8"?>
-
<!--
-
Copyright 2011 xxx Inc.
-
-->
-
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
-
android:label="@string/search_label"
-
android:hint="@string/search_hint"
-
<!-- Authority設置成對應provider的全稱 -->
-
android:searchSuggestAuthority="com.xxx.alimobile.util.SearchSuggestionsProvider"
-
android:searchSuggestIntentAction="android.intent.action.SEARCH"
-
android:searchSuggestThreshold="0"
-
android:searchSuggestSelection=" ? " />
複製代碼
3 在AndroidManifest.xml中,給處理Search請求的頁面加入intent過濾器和searchable配置文件
-
<activity
-
android:name=".ui.WebViewActivity"
-
android:theme="@style/Theme.AliMobile"
-
android:screenOrientation="portrait"
-
android:configChanges="orientation|keyboard|keyboardHidden">
-
<intent-filter>
-
<action android:name="android.intent.action.SEARCH" />
-
</intent-filter>
-
<meta-data
-
android:name="android.app.searchable"
-
android:resource="@xml/searchable" />
-
</activity>
複製代碼
4 判斷是不是action_search intent事件發起的,然後處理。
-
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
-
String queryString = intent.getStringExtra(SearchManager.QUERY);
-
strUrl = "http://search1.wap.taobao.com/s/search.htm?q=" + queryString;
-
}
複製代碼
後面還剩下suggestion的配置, 參考此篇技術文章: http://www.apkbus.com/android-14572-1-1.html 5 SearchSuggestionProvider類,繼承自android.content.SearchRecentSuggestionsProvider,直接使用sdk中的簡單實現。
-
import android.content.SearchRecentSuggestionsProvider;
-
-
public class SearchSuggestionsProvider extends SearchRecentSuggestionsProvider {
-
public final static String AUTHORITY = "com.xxx.alimobile.util.SearchSuggestionsProvider";
-
public final static int MODE = DATABASE_MODE_QUERIES;
-
-
public SearchSuggestionsProvider() {
-
setupSuggestions(AUTHORITY, MODE);
-
}
-
}
-
複製代碼
6 在第4步基礎上加入保存功能,每次使用搜索後調用provider進行保存搜索的字段。
-
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
-
String queryString = intent.getStringExtra(SearchManager.QUERY);
-
strUrl = "http://search1.wap.taobao.com/s/search.htm?q=" + queryString;
-
// SAVE THE SEARCH QUERY
-
SearchRecentSuggestions suggestions =
-
new SearchRecentSuggestions(
-
this, SearchSuggestionsProvider.AUTHORITY,
-
SearchSuggestionsProvider.MODE);
-
suggestions.saveRecentQuery(queryString, null);
-
} else {
-
strUrl = (String) intent.getExtras().get("goUrl");
-
}
複製代碼
7 AndroidManifest.xml中加入provider聲明。
-
<provider
-
android:name=".util.SearchSuggestionsProvider"
-
android:authorities="com.xxx.alimobile.util.SearchSuggestionsProvider">
-
</provider>
複製代碼
|