一、配置搜索描述文件
要在res中的xml文件加创建sreachable.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<searchable
xmlns:android="/apk/res/android"
android:hint="@string/searchLable"
android:label="@string/searchLable"
android:searchSuggestAuthority="com.glacier.ui.SearchSuggestionProvider"
android:searchSuggestSelection=" ? ">
</searchable>
二、填写配置文件信息
1.搜索框的配置
<!-- 搜索动作 -->
<intent-filter >
<action android:name="android.intent.action.SEARCH" >
</action>
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value="MainActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" >
</meta-data>
2.保存内容的配置
<provider
android:authorities="com.glacier.ui.SearchSuggestionProvider"
android:name="com.glacier.ui.SearchSuggestionProvider" >
</provider>
三、调用启动搜索框方法
//弹出搜索框
onSearchRequested();
可以重新写系统的方法做些必要的内容加载其他
@Override
public boolean onSearchRequested(){
//打开浮动搜索框(第一个参数默认添加到搜索框的值)
startSearch(null, false, null, false);
return true;
}
//得到搜索结果
@Override
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
//获得搜索框里值
query=intent.getStringExtra(SearchManager.QUERY);
System.out.println(query);
//保存搜索记录
SearchRecentSuggestions suggestions=new SearchRecentSuggestions(MainActivity.this,
SearchSuggestionProvider.AUTHORITY, SearchSuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
System.out.println("保存成功");
}
四、记得要写存储的地方
import android.content.SearchRecentSuggestionsProvider;
public class SearchSuggestionProvider extends SearchRecentSuggestionsProvider {
public final static String AUTHORITY="com.glacier.ui.SearchSuggestionProvider";
public final static int MODE=DATABASE_MODE_QUERIES;
public SearchSuggestionProvider(){
super();
setupSuggestions(AUTHORITY, MODE);
}
}