android textview 关键字高亮显示

本文介绍如何使用SpannableString和正则表达式在Android TextView中搜索并高亮显示关键字。通过setSpan方法设置文本样式,实现特定字符串的视觉突出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:搜索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…endof the text, or move the object to that range if it was already attached elsewhere. SeeSpannedfor 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 ofCharacterStyleandParagraphStyle, andTextWatcherandSpanWatcher.

这个函数的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);
要是大数据量的时候,每次搜索都重新setText可能效率上非常不好,这里提供一个看过源码的建议,在一次setText(spannable s) 之后,每次getText获取的就是spannable了,所以不用每次更改和重新载入数据,直接更改就可以了。
参考
http://yuanzhifei89.iteye.com/blog/983944 这个页面有些各种各样的样式和实现点击跳转的方法即Linkify
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值