Android开发之代码开发部分字符串变色

方法如下:

方法一:

/**
     * 字符串截取变红
     *
     * @param otherString  你要变色的字符,可为null
     * @param changeString 你要变色的字符
     * @param allString    整个字符串
     * @param number       要变色的控件
     */
    public void stringChangeColor(CheckBox number, String allString, String changeString, String otherString) {
        int fstart = allString.indexOf(changeString);
        int fend = fstart + changeString.length();
        SpannableStringBuilder style = new SpannableStringBuilder(allString);
        if (!"".equals(otherString) && otherString != null) {
            int bstart = allString.indexOf(otherString);
            int bend = bstart + otherString.length();
            style.setSpan(new ForegroundColorSpan(Color.parseColor("#586E98")), bstart, bend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#586E98")), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        number.setText(style);
    }

直接调用即可:

 stringChangeColor(registerClause, getString(R.string.reapal_protocol), "《扬宏豕慧用户协议》、《法律声明》、《隐私协议》", null);

方法二:

 /**
     * 设置部分字符串变色的方法
     *
     * @param textView 文本控件
     * @param str      全部的字符
     * @param start    字符串变色开始的位置
     * @param end      字符串变色结束的位置
     */
    private void setSelectTextColor(TextView textView, String str, int start, int end) {
        //方法二:
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        //设置指定位置textview的背景颜色
//        style.setSpan(new BackgroundColorSpan(Color.RED),2,5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置指定位置文字的颜色
//        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorMain)), str.length() - start, str.length() - end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置部分字符串变色以及加粗的方法
        //style 为0 即是正常的,还有Typeface.BOLD(粗体) Typeface.ITALIC(斜体)等
        //size  为0 即采用原始的正常的 size大小 
        style.setSpan(new TextAppearanceSpan(null, Typeface.BOLD, 0, ColorStateList.valueOf(getResources().getColor(R.color.colorMain)), null), str.length() - start, str.length() - end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        textView.setText(style);
    }

方法三:使用正则匹配

package com.noboauto.module_search.util

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import com.noboauto.common.global.GlobalContext
import com.noboauto.module_search.R
import java.util.regex.Pattern

/**
 *
 * @author xiayiye5
 * @date 2021/9/29 10:44
 */
object ChangeTextColorUtils {
    /**
     * @param text 整个字符串
     * @param keyword 要变色的字符串
     */
    fun getSpannableString(text: String, keyword: String): SpannableString {
        val sb = StringBuffer()
        for (element in keyword) {
            val s = element.toString() + ""
            if (pattern(REGULAR_EXPRESSION, s)) {
                sb.append("\\").append(s)
            } else {
                sb.append(s)
            }
        }
        return matcherSearchTitle(
            ContextCompat.getColor(mContext, R.color.red),
            text,
            sb.toString()
        )
    }

    private fun matcherSearchTitle(color: Int, text: String, keyword: String): SpannableString {
        val s = SpannableString(text)
        val p = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE)
        val m = p.matcher(s)
        while (m.find()) {
            val start = m.start()
            val end = m.end()
            s.setSpan(
                ForegroundColorSpan(color), start, end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        return s
    }

    /**
     * 正则表达式匹配
     *
     * @param regularExpression
     * @param str
     * @return
     */
    private fun pattern(regularExpression: String, str: String): Boolean {
        return Pattern.compile(regularExpression).matcher(str).matches()
    }

    private val REGULAR_EXPRESSION =
        "(" +
                "\\{|" +
                "\\}|" +
                "\\(|" +
                "\\)|" +
                "\\[|" +
                "\\]|" +
                "\\+|" +
                "\\?|" +
                "\\$|" +
                "\\^|" +
                "\\||" +
                "\\.|" +
                "\\-|" +
                "\\\\|" +
                "\\*" +
                ")"
}

调用方法如下:

holder.recommendWord.text = ChangeTextColorUtils.getSpannableString("1 水浒传","1")

实现效果如下:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值