搜索功能实现记录
1、简单效果图
2、搜索关键字高亮显示
参数:color为高亮的颜色;text为搜索的推荐词;keyword为关键字,即输入框中输入的文字。
原理就是封装一个matcherSearchTitle()的静态方法,用SpannableString去处理关键字高亮显示,处理完成后方法返回处理好的SpannableString。
/**
* 关键字高亮变色
*
* @param color 变化的色值
* @param text 文字
* @param keyword 文字中的关键字
* @return 结果SpannableString
*/
public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
SpannableString s = new SpannableString(text);
keyword=escapeExprSpecialWord(keyword);
text=escapeExprSpecialWord(text);
if (text.contains(keyword)&&!TextUtils.isEmpty(keyword)){
try {
Pattern p = Pattern.compile(keyword);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}catch (Exception e){
}
}
return s;
}
/**
* 转义正则特殊字符 ($()*+.[]?\^{},|)
*
* @param keyword
* @return keyword
*/
public static String escapeExprSpecialWord(String keyword) {
if (!TextUtils.isEmpty(keyword)) {
String[] fbsArr = {
"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\\" + key);
}
}
}
return keyword;
}
3、搜索历史实现
3.1、SearchLayout.java
首先是一个自定义搜索标签布局,maxLine控制标签栏最大行数。
public class SearchLayout extends ViewGroup {
//存储所有子view
private List<List<View>> mAllChildViews = new ArrayList<>();
private int maxLine = 2;
//每一行的高度
private List<Integer> mLineHeight = new ArrayList<>();
public SearchLayout(Context context){
this(context,null);
}
public SearchLayout(Context context, AttributeSet attrs){
this(context,attrs,0);
}
public SearchLayout(Context context,AttributeSet attrs,int defStyle){
super(context,attrs,defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
//父控件传进来的宽度和高度以及对应的测量模式
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int sizeHeight = MeasureSpec