需求:搜索TextView里面的关键字,并高亮显示。
实现方法:
利用SpannableString 的特性,搜索TextView的要显示的字符串,将相应的关键字标记为高亮
设计到的api
1. SpannableString
这是一个很奇妙的东西,利用他你可以实现qq聊天记录自动替换表情文字的效果。当然,这里我们只要将文字设计成高亮就可以了
2. 这里有个api函数,
public abstract voidsetSpan(Objectwhat, int start, int end, int flags)
Since:
API Level 1
Attach the specified markup object to the rangestart…end
of the text, or move the object to that range if it was already attached elsewhere. SeeSpanned
for an explanation of what the flags mean. The object can be one that has meaning only within your application, or it can be one that the text system will use to affect text display or behavior. Some noteworthy ones are the subclasses ofCharacterStyle
andParagraphStyle
, andTextWatcher
andSpanWatcher
.
这个函数的object是给定的样式,或者替换什么的,start和end指定了采用样式的位置,flags我不知道是什么,这里用源码里面的Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
3. 搜索方法,这里只是一个简单的测试,用正则实现的搜索。
上代码
TextViewtv
=
(TextView)findViewById(R.id.hello);
SpannableStrings = new SpannableString(getResources().getString(R.string.linkify));
Patternp = Pattern.compile( " abc " );
Matcherm = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.rgb(250, 102, 100)), start, end,//这里可以用Color.red等,但是不能用//R.color.red.这样得不到想要的颜色。
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s);
SpannableStrings = new SpannableString(getResources().getString(R.string.linkify));
Patternp = Pattern.compile( " abc " );
Matcherm = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.rgb(250, 102, 100)), start, end,//这里可以用Color.red等,但是不能用//R.color.red.这样得不到想要的颜色。
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s);
要是大数据量的时候,每次搜索都重新setText可能效率上非常不好,这里提供一个看过源码的建议,在一次setText(spannable s) 之后,每次getText获取的就是spannable了,所以不用每次更改和重新载入数据,直接更改就可以了。
参考
http://yuanzhifei89.iteye.com/blog/983944 这个页面有些各种各样的样式和实现点击跳转的方法即Linkify