android TextView 实现关键字高亮
需求:搜索TextView里面的关键字,并高亮显示。
实现方法:
利用SpannableString 的特性,搜索TextView的要显示的字符串,将相应的关键字标记为高亮
设计到的api
1. SpannableString
这是一个很奇妙的东西,利用他你可以实现qq聊天记录自动替换表情文字的效果。当然,这里我们只要将文字设计成高亮就可以了
2. 这里有个api函数,
public abstract void setSpan (Object what, int start, int end, int flags)
Since: API Level 1
Attach the specified markup object to the range start…end
of the text, or move the object to that range if it was already attached elsewhere. See Spanned
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 of CharacterStyle
and ParagraphStyle
, and TextWatcher
and SpanWatcher
.
这个函数的object是给定的样式,或者替换什么的,start和end指定了采用样式的位置,flags我不知道是什么,这里用源码里面的Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
3. 搜索方法,这里只是一个简单的测试,用正则实现的搜索。
上代码
TextView tv = (TextView) findViewById(R.id.hello); SpannableString s = new SpannableString(getResources().getString(R.string.linkify)); Pattern p = Pattern.compile("abc"); Matcher m = p.matcher(s); while (m.find()) { int start = m.start(); int end = m.end(); s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } tv.setText(s);
要是大数据量的时候,每次搜索都重新setText可能效率上非常不好,这里提供一个看过源码的建议,在一次setText(spannable s) 之后,每次getText获取的就是spannable了,所以不用每次更改和重新载入数据,直接更改就可以了。
参考
http://yuanzhifei89.iteye.com/blog/983944 这个页面有些各种各样的样式和实现点击跳转的方法即Linkify
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端