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了,所以不用每次更改和重新载入数据,直接更改就可以了。
参考

转载于:https://www.cnblogs.com/sishuiliuyun/articles/3171072.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值