//进行子View进行布局
child.layout(cLeft, cTop, cRight, cBottom);
left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
left = 0;
top += lineHeight;
}
}
/**
- 与当前ViewGroup对应的LayoutParams
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
}
第二步:新建一个SharePreference工具类,用来保存、读取、清除历史搜索记录,这里贴上这三个方法的代码
/**
-
保存搜索记录
-
@param keyword
*/
public void save(String keyword) {
// 获取搜索框信息
SharedPreferences mysp = mContext.getSharedPreferences(“search_history”, 0);
String old_text = mysp.getString(“history”, “”);
// 利用StringBuilder.append新增内容,逗号便于读取内容时用逗号拆分开
StringBuilder builder = new StringBuilder(old_text);
builder.append(keyword + “,”);
// 判断搜索内容是否已经存在于历史文件,已存在则不重复添加
if (!old_text.contains(keyword + “,”)) {
SharedPreferences.Editor myeditor = mysp.edit();
myeditor.putString(“history”, builder.toString());
myeditor.commit();
}
}
public String[] getHistoryList() {
// 获取搜索记录文件内容
SharedPreferences sp = mContext.getSharedPreferences(“search_history”, 0);
String history = sp.getString(“history”, “”);
// 用逗号分割内容返回数组
String[] history_arr = history.split(",");
// 保留前50条数据
if (history_arr.length > 50) {
String[] newArrays = new String[50];
System.arraycopy(history_arr, 0, newArrays, 0, 50);
}
return history_arr;
}
/**
- 清除搜索记录
*/
public void cleanHistory() {
SharedPreferences sp = mContext.getSharedPreferences(“search_history”, 0);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.commit();
}
最后呢,就到了关键的一步啦,在Activity里进行读写初始化操作啦。
package cn.cnpp.searchhistory;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import a