private void initSearchHistory() { List<String> list = SharedPreferencesUtil.getInstance().getObject("searchHistory", List.class); mHisAdapter.clear(); if (list != null && list.size() > 0) { tvClear.setEnabled(true); mHisAdapter.addAll(list); } else { tvClear.setEnabled(false); } mHisAdapter.notifyDataSetChanged(); }
/** * 保存搜索记录.不重复,最多保存20条 * * @param query */ private void saveSearchHistory(String query) { List<String> list = SharedPreferencesUtil.getInstance().getObject("searchHistory", List.class); if (list == null) { list = new ArrayList<>(); list.add(query); } else { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (TextUtils.equals(query, item)) { iterator.remove(); } } list.add(0, query); } int size = list.size(); if (size > 20) { // 最多保存20条 for (int i = size - 1; i >= 20; i--) { list.remove(i); } } SharedPreferencesUtil.getInstance().putObject("searchHistory", list); initSearchHistory(); }
@OnClick(R.id.tvClear) public void clearSearchHistory() { SharedPreferencesUtil.getInstance().putObject("searchHistory", null); initSearchHistory(); }