Android关键字高亮、关键字背景、是否忽略大小写的相关处理

一直也是用这个Textview关键字高亮的相关处理,经过一些个需求变化,这里记录下这个工具类,以后备用:

HighLightKeyWordUtil.java

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HighLightKeyWordUtil {
    /**
     * @param color 关键字颜色
     * @param text 文本
     * @param keyword 关键字
     * @return
     */
    public static SpannableString getHighLightKeyWord(int color, String text, String keyword, boolean ignoreCase) {
        SpannableString s = new SpannableString(text);
        String wordReg = keyword;
        if (ignoreCase){
            wordReg = "(?i)"+ keyword;    ///< 用(?i)来忽略大小写
        }
        Pattern p = Pattern.compile(wordReg);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return s;
    }

    /**
     * @param color 关键字颜色
     * @param text 文本
     * @param keyword 多个关键字数组
     * @return
     */
    public static SpannableString getHighLightKeyWord(int color, String text,String[] keyword, boolean ignoreCase) {
        SpannableString s = new SpannableString(text);
        for (int i = 0; i < keyword.length; i++) {
            String wordReg = keyword[i];
            if (ignoreCase){
                wordReg = "(?i)"+ keyword[i];    ///< 用(?i)来忽略大小写
            }
            Pattern p = Pattern.compile(wordReg);
            Matcher m = p.matcher(s);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new ForegroundColorSpan(color), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return s;
    }

    /**
     * @param color 关键字背景颜色
     * @param text 文本
     * @param keyword 关键字
     * @return
     */
    public static SpannableString getBackgroudKeyWord(int tvcolor, int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        Pattern p = Pattern.compile(keyword);
        Matcher m = p.matcher(s);
        //while (m.find()) {
        if (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new RoundBackgroundColorSpan(color, tvcolor, 10), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return s;
    }

    /**
     *
     * @param tvcolor 关键字颜色
     * @param color   关键字背景颜色
     * @param text    文本
     * @param keywords 多个关键字数组
     * @return
     */
    public static SpannableString getBackgroudKeyWord(int tvcolor, int color, String text, String[] keywords) {
        SpannableString s = new SpannableString(text);
        for (int i = 0; i < keywords.length; i++) {
            Pattern p = Pattern.compile(keywords[i]);
            Matcher m = p.matcher(s);
            //while (m.find()) {
            if (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new RoundBackgroundColorSpan(color, tvcolor, 10), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return s;
    }

    /**
     *
     * @param tvcolor 关键字颜色数组
     * @param color 关键字背景颜色数组
     * @param s SpannableString
     * @param keywords 多个关键字数组
     * @return
     */
    public static SpannableString getBackgroudKeyWord(int[] tvcolor, int[] color, SpannableString s, String[] keywords) {
        int strLength = 0;
        for (int i = 0; i < keywords.length; i++) {
            ///< 必须是开头的才标记背景,所以索引必须小于开头内容长度
            strLength += keywords[i].length();

            Pattern p = Pattern.compile(keywords[i]);
            Matcher m = p.matcher(s);
            ///< 只找开头的,标题中的不找
            //while (m.find()) {
            //if (m.find()) {
            if (m.find() && m.start() < strLength) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new RoundBackgroundColorSpan(color[i], tvcolor[i], 10), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return s;
    }

    /**
     *
     * @param tvcolor 关键字颜色数组
     * @param color  关键字背景颜色数组
     * @param text   文本
     * @param keywords 多个关键字数组
     * @return
     */
    public static SpannableString getBackgroudKeyWord(int[] tvcolor, int[] color, String text, String[] keywords) {
        SpannableString s = new SpannableString(text);
        int strLength = 0;
        for (int i = 0; i < keywords.length; i++) {
            ///< 必须是开头的才标记背景,所以索引必须小于开头内容长度
            strLength += keywords[i].length();

            Pattern p = Pattern.compile(keywords[i]);
            Matcher m = p.matcher(s);
            ///< 只找开头的,标题中的不找
            //while (m.find()) {
            //if (m.find()) {
            if (m.find() && m.start() < strLength) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new RoundBackgroundColorSpan(color[i], tvcolor[i], 10), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return s;
    }
}

注意一下大小写的处理

image

注意一下关键字背景高亮只处理字符串开始出现的关键字的情况:

image

其中: RoundBackgroundColorSpan.java

package com.lieyunwang.app.common.utils.textview;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

/*
 *@Description: 字体添加圆角背景
 *@Author: hl
 *@Time: 2018/7/10 11:34
 */
public class RoundBackgroundColorSpan extends ReplacementSpan {
    private int bgColor;
    private int textColor;
    private int mSize;
    private int radius;

    public RoundBackgroundColorSpan(int bgColor, int textColor, int radius) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
        this.radius = radius;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //设置宽度为文字宽度加16dp
        return (mSize = (int) (paint.measureText(text, start, end) + 2 * radius));
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int originalColor = paint.getColor();
        paint.setColor(this.bgColor);
        paint.setAntiAlias(true);// 设置画笔的锯齿效果
        //画圆角矩形背景
        RectF oval = new RectF(
                x > 5 ? (x - 5) : x,
                (y + paint.ascent()) > 5 ? ((y + paint.ascent()) - 5): (y + paint.ascent()),
                x + mSize + 5,
                y + paint.descent() + 5);
        //设置文字背景矩形,x为span其实左上角相对整个TextView的x值,y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘,paint.descent()获得文字下边缘
        canvas.drawRoundRect(oval, radius, radius, paint);//绘制圆角矩形,第二个参数是x半径,第三个参数是y半径
        paint.setColor(this.textColor);
        //画文字
        canvas.drawText(text, start, end, x + radius, y, paint);
        //将paint复原
        paint.setColor(originalColor);
    }
}

使用示例:

((TextView) getView(viewId)).setText(HighLightKeyWordUtil.getBackgroudKeyWord(
                new int[]{Color.parseColor("#ffffff"), Color.parseColor("#ffffff")},
                new int[]{Color.parseColor("#febc48"), Color.parseColor("#f13b2f")},
                content, new String[]{"独家", "首发"}));

效果:


image.png

具体可以根据实际需求进行修改和完善即可....代码不是特别精简,可以考虑优化下,提出共用方法。小白觉得还好就懒得提了....

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容