【有人@我】Android中高亮變色顯示文本中的關鍵字

應該是很久沒有寫有關技術類的文章了,前天還有人在羣裏問我,說羣主很長時間沒有分享乾貨了,今天分享一篇Android中TextView在大段的文字內容中如何讓關鍵字高亮變色的文章 ,但願對你們有所幫助,我終於在歪路上回歸正途了。這個篇文章在平時應該還算比較經常使用吧,若是你會了,就不用看了,若是還不會,能夠看一眼,很是簡單。java

 

今天分享的文章大概內容是在TextView中如何使大段的文字內容中關鍵字變色高亮顯示的,分爲一個關鍵字高亮變色顯示和多個關鍵字一塊兒高亮變色顯示。我已經封裝成了KeywordUtil工具類,能夠直接調用,效果圖以下:android

 

 

具體代碼以下:程序員

package net.loonggg.test;

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

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

public class KeywordUtil {

    /**
     * 關鍵字高亮變色
     * 
     * @param color
     *            變化的色值
     * @param text
     *            文字
     * @param keyword
     *            文字中的關鍵字
     * @return
     */
    public static SpannableString matcherSearchTitle(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 matcherSearchTitle(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;
    }
}

其實看完代碼就知道了,很是簡單。你們能夠試一試哦!獲取demo的方法跟之前同樣,只需在公衆號裏回覆關鍵字「5」便可得到。數組

 

【特別推薦↓】微信


 微信公衆號:smart_android ,公衆號[非著名程序員]多是東半球最好的技術分享公衆號。天天,每週定時推送一些有關移動開發的原創文章和教程。工具

「非著名程序員」本人創建了一個高端Android微信交流羣,若是有想加入的請先加我我的微信號:loonggg ,具體加入條件很是簡單,加我我的微信號時,請備註爲:加羣,到時會告訴你具體的加入流程,感謝🙏每位開發者的配合。spa

相關文章
相關標籤/搜索