|
经过以下几个部分的实现和配置,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> |
|