搜索关键字变红,指定字段变色
有时候我们搜索中的关键字需要变红或者变为别的颜色,我自己重写了textview。使用起来特别方便
使用步骤
1,把下面自定义的MyTextView 复制到项目中
import android.content.Context; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.widget.TextView;
import java.util.ArrayList; import java.util.List;
//制定字体变色,自定义textview public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSpecifiedTextsColor(String text, String specifiedTexts, int color) {
List<Integer> sTextsStartList = new ArrayList<>();
int sTextLength = specifiedTexts.length();
String temp = text;
int lengthFront = 0;//记录被找出后前面的字段的长度
int start = -1;
do {
start = temp.indexOf(specifiedTexts);
if (start != -1) {
start = start + lengthFront;
sTextsStartList.add(start);
lengthFront = start + sTextLength;
temp = text.substring(lengthFront);
}
} while (start != -1);
SpannableStringBuilder styledText = new SpannableStringBuilder(text);
for (Integer i : sTextsStartList) {
styledText.setSpan(
new ForegroundColorSpan(color),
i,
i + sTextLength,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(styledText);
}
}
2,使用只需要一行代码就可以完事 public class TextActivity04 extends Activity { private MyTextView textView;
public String result = "关键字变色,特别简单,只需要一行代码,就可以实现关键字变红";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_04_layout);
textView = (MyTextView)findViewById(R.id.tv);
textView.setSpecifiedTextsColor(result, "关键字", Color.parseColor("#FF0000"));
/*
textView.setSpecifiedTextsColor(result, "关键字", Color.parseColor("#FF0000"))中result可以换成你的搜索结果
关键字直接换成你的EditText中输入的关键字就可以啦
*/
}
}
效果图
源码下载地址
https://github.com/qiushi123/BlurBehindActivity