一、如何调出搜索框
在Androidmainfest中给Activity定义
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
在Activity调用onSearchRequested()方法调出搜索框。上面的android:resource没有也能调出搜索框。
二、如何定义android:resource里面的内容
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:searchSuggestIntentAction="android.intent.action.VIEW"
android:includeInGlobalSearch="true"
android:searchSuggestAuthority="com.yeezone.timezone.provider"
android:searchSuggestIntentData="content://com.yeezone.timezone.provider/data"
android:searchSuggestSelection=" ?">
</searchable>
android:label 必须与Activity的label或者Application的label一致。
android:hint 搜索框内灰色的提示文字。
android:searchSuggestIntentAction 得到选择项时获取的intent中的Action(intent.getAction),随便定义。
android:searchSuggestIntentData 得到选择项时获取的intent中的data值(intent.getData),得到的Uri带有id后缀。
android:searchSuggestAuthority 查询的contentProvider的Authority。
android:searchSuggestSelection=" ?" 设置后provider里selectionArgs项就不会为null了。代表selectionArgs 。
所有定义见官网:http://developer.android.com/guide/topics/search/searchable-config.html
三、如何实现搜索的contentProvider。
当在搜索框内输入文字时(focus时也会触发)会查询ContentProvider,查询的matcher字符串为SearchManager.SUGGEST_URI_PATH_QUERY,如:
matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);输入的内容存在了selectionArgs数组的第一位,下标为0。查完的结果返回时注意:
返回的cursor中,必须要有列名为如下的列:
BaseColumns._ID
SearchManager.SUGGEST_COLUMN_TEXT_1
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
如果返回的cursor中有SearchManager.SUGGEST_COLUMN_TEXT_2,那么搜索结果就显示两行,否则一行。
四、如何得到搜索后选择的结果
给搜索的Activity在Androidmainifest中设置android:launchMode="singleTop"保证Activity只启动一次,选择搜索结果后Activity的onNewIntent(Intent intent)方法会被调用,重写此方法。如果intent的action是android:searchSuggestIntentAction中定义的,那么代表搜索后选择结果返回了。通过intent.getData()得到Uri,此uri的string为
android:searchSuggestIntentData定义的+/+被选择项的_id。利用此uri查询这一条被选择项的详细信息。
本文详细介绍如何在Android应用中配置和实现搜索功能,包括调用搜索框的方法、定义搜索配置文件、实现搜索的ContentProvider及获取搜索结果。
424

被折叠的 条评论
为什么被折叠?



