主要通過SharedPreferences進(jìn)行存儲伪朽,難點(diǎn)主要是1.倒序顯示 2.去重 3.最多顯示n條轴咱。話不多說看代碼
private final static String PREFERENCE_NAME = "superservice_ly";
private final static String SEARCH_HISTORY="linya_history";
// 保存搜索記錄
public static void saveSearchHistory(String inputText) {
SharedPreferences sp = App.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
if (TextUtils.isEmpty(inputText)) {
return;
}
String longHistory = sp.getString(SEARCH_HISTORY, ""); //獲取之前保存的歷史記錄
String[] tmpHistory = longHistory.split(","); //逗號截取 保存在數(shù)組中
List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory)); //將改數(shù)組轉(zhuǎn)換成ArrayList
SharedPreferences.Editor editor = sp.edit();
if (historyList.size() > 0) {
//1.移除之前重復(fù)添加的元素
for (int i = 0; i < historyList.size(); i++) {
if (inputText.equals(historyList.get(i))) {
historyList.remove(i);
break;
}
}
historyList.add(0, inputText); //將新輸入的文字添加集合的第0位也就是最前面(2.倒序)
if (historyList.size() > 8) {
historyList.remove(historyList.size() - 1); //3.最多保存8條搜索記錄 刪除最早搜索的那一項(xiàng)
}
//逗號拼接
StringBuilder sb = new StringBuilder();
for (int i = 0; i < historyList.size(); i++) {
sb.append(historyList.get(i) + ",");
}
//保存到sp
editor.putString(SEARCH_HISTORY, sb.toString());
editor.commit();
} else {
//之前未添加過
editor.putString(SEARCH_HISTORY, inputText + ",");
editor.commit();
}
}
//獲取搜索記錄
public static List<String> getSearchHistory(){
SharedPreferences sp = App.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
String longHistory =sp.getString(SEARCH_HISTORY, "");
String[] tmpHistory = longHistory.split(","); //split后長度為1有一個空串對象
List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory));
if (historyList.size() == 1 && historyList.get(0).equals("")) { //如果沒有搜索記錄,split之后第0位是個空串的情況下
historyList.clear(); //清空集合,這個很關(guān)鍵
}
return historyList;
}
代碼就這些朴肺,放到你的工具類里面窖剑,在你需要的地方調(diào)用就好了。