一、配置搜尋描述檔案
要在res中的xml檔案加建立sreachable.xml,內容如下:
<?xml version="1.0" encoding="utf-8"?>
<searchable
xmlns:android="http://schemas.android.com/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);
}
}