Android 高亮關鍵字TextView

weixin_34236869發表於2018-06-09

最近有需求做一個標記關鍵字的文字功能,僅此記錄分享一下

需求很簡單,就是標記搜尋的關鍵字,這裡是需要標記每一個字,具體效果如下:

595349-a5ed60dc790841c1.png
效果圖

其實思路比較簡單,對文字中的文字進行匹配,匹配後使用SpannableString(或者SpannableStringBuilder)修改文字的顏色。主要程式碼如下:

public SpannableStringBuilder matcherSignText() {
    if (TextUtils.isEmpty(mOriginalText)) {
        return new SpannableStringBuilder("");
    }
    if (TextUtils.isEmpty(mSignText)) {
        return new SpannableStringBuilder(mOriginalText);
    }
    //關鍵程式碼
    SpannableStringBuilder builder = new SpannableStringBuilder(mOriginalText);
    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(mSignTextColor);
    for (int index = 0; index < mSignText.length(); index++) {
        final char c = mSignText.charAt(index);
        Pattern p = Pattern.compile(String.valueOf(c));
        Matcher m = p.matcher(mOriginalText);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            builder.setSpan(foregroundColorSpan, start, end, 
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return builder;
}

為了方便使用,為關鍵字和關鍵字顏色定義了自定義屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="SignKeyWordTextView">
        <attr name="signText" format="string"/>
        <attr name="signTextColor" format="color"/>
    </declare-styleable>
    
</resources>

在xml中使用相對比較方便

<com.mrtrying.SignKeyWordTextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:lines="1"
    android:textColor="#c4c4c4"
    android:textSize="@dimen/sp_15"
    app:signTextColor="#FFDA44"/>

最後上原始碼

package com.mrtrying;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import com.quze.lbsvideo.R;

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

/**
 * Description :
 * PackageName : com.mrtrying
 * Created by mrtrying on 2018/6/7 10:24.
 * e_mail : ztanzeyu@gmail.com
 */
public class SignKeyWordTextView extends AppCompatTextView {

    //原始文字
    private String mOriginalText = "";
    //關鍵字
    private String mSignText;
    //關鍵字顏色 
    private int mSignTextColor;

    public SignKeyWordTextView(Context context) {
        super(context);
    }

    public SignKeyWordTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeAttrs(attrs);
    }

    //初始化自定義屬性
    private void initializeAttrs(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.SignKeyWordTextView);
        //獲取關鍵字
        mSignText = typedArray.getString(R.styleable.SignKeyWordTextView_signText);
        //獲取關鍵字顏色
        mSignTextColor = typedArray.getColor(R.styleable.SignKeyWordTextView_signTextColor, getTextColors().getDefaultColor());
        typedArray.recycle();
    }

    //重寫setText方法
    @Override
    public void setText(CharSequence text, BufferType type) {
        this.mOriginalText = text.toString();
        super.setText(matcherSignText(), type);
    }

    /**
     * 匹配關鍵字,並返回SpannableStringBuilder物件
     * @return
     */
    private SpannableStringBuilder matcherSignText() {
        if (TextUtils.isEmpty(mOriginalText)) {
            return new SpannableStringBuilder("");
        }
        if (TextUtils.isEmpty(mSignText)) {
            return new SpannableStringBuilder(mOriginalText);
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(mOriginalText);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(mSignTextColor);
        for (int index = 0; index < mSignText.length(); index++) {
            final char c = mSignText.charAt(index);
            Pattern p = Pattern.compile(String.valueOf(c));
            Matcher m = p.matcher(mOriginalText);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                builder.setSpan(foregroundColorSpan, start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return builder;
    }

    /**
     * 設定關鍵字
     * @param signText 關鍵字
     */
    public void setSignText(String signText) {
        mSignText = signText;
        setText(mOriginalText);
    }

    /**
     * 設定關鍵字顏色
     * @param signTextColor 關鍵字顏色
     */
    public void setSignTextColor(int signTextColor) {
        mSignTextColor = signTextColor;
        setText(mOriginalText);
    }

}

相關文章