美文网首页安卓应用层
Android中TextView的文本内容中指定关键字高亮显示

Android中TextView的文本内容中指定关键字高亮显示

作者: millerkevin | 来源:发表于2017-04-15 22:42 被阅读536次

让TextView的文本中指定关键字高亮显示的工具类

public class HighLightKeyWordUtil {  
  
    /** 
     * @param color 关键字颜色 
     * @param text 文本 
     * @param keyword 关键字 
     * @return 
     */  
    public static SpannableString getHighLightKeyWord(int color, String text,String keyword) {  
        SpannableString s = new SpannableString(text);  
        Pattern p = Pattern.compile(keyword);  
        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) {  
        SpannableString s = new SpannableString(text);  
        for (int i = 0; i < keyword.length; i++) {  
            Pattern p = Pattern.compile(keyword[i]);  
            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;  
  
    }  
  
}  

相关文章

网友评论

    本文标题:Android中TextView的文本内容中指定关键字高亮显示

    本文链接:https://www.haomeiwen.com/subject/kouoattx.html