android在一个TextView中设置不同字体大小、不同字体颜色封装

一、概述

  在开发过程中遇到过这样一种业务,有很多单行文本字体。字符串中每一部分的字体样式、大小、颜色都不相同。传统的做法是放多个TextView以达到效果。

  但是当这个页面中的这样的元素非常多,且非常复杂的时候,就会出现页面加载缓慢的问题(view加载=深度(递归)+平铺),也就是页面元素越多,层级越深加载速度越慢。

  此时如果能把本来要用四五个TextView才能完成的事情用一个TextView完成,这样就能大大提高页面加载速度。

  示例图:

 

  

二、代码示例(直接复制粘贴可用)

  1.封装类:ColorSizeTextView.kt

package com.yw.custommutilimageadapter.widget

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView
import com.yw.custommutilimageadapter.R
import java.lang.StringBuilder


/**
 * 可改变字颜色和字体大小的TextView
 * 即一个字体中可以有不同的字体颜色和字体大小
 */
class ColorSizeTextView(context: Context, attrs: AttributeSet?) :
    AppCompatTextView(context, attrs) {
    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.ColorSizeTextView)

        val textColor1 = a.getColor(R.styleable.ColorSizeTextView_textColor1, Color.BLACK)
        val textSize1 = a.getDimension(R.styleable.ColorSizeTextView_textSize1, 12f)
        val textContent1 = a.getString(R.styleable.ColorSizeTextView_textContent1)

        val textColor2 = a.getColor(R.styleable.ColorSizeTextView_textColor2, Color.BLACK)
        val textSize2 = a.getDimension(R.styleable.ColorSizeTextView_textSize2, 12f)
        val textContent2 = a.getString(R.styleable.ColorSizeTextView_textContent2)

        val textColor3 = a.getColor(R.styleable.ColorSizeTextView_textColor3, Color.BLACK)
        val textSize3 = a.getDimension(R.styleable.ColorSizeTextView_textSize3, 12f)
        val textContent3 = a.getString(R.styleable.ColorSizeTextView_textContent3)
        val isLayout = a.getBoolean(R.styleable.ColorSizeTextView_isLayout, false)


        Log.e("ColorSizeTextView:", "$textSize1,$textSize2,$textSize3")

        if (isLayout) {
            // 创建一个SpannableString对象
            val spannableString = SpannableString("$textContent1$textContent2$textContent3")
            // 设置第一部分文本的字体大小和颜色
            spannableString.setSpan(
                AbsoluteSizeSpan(textSize1.toInt()),
                0,
                textContent1?.length!!,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(textColor1),
                0,
                textContent1?.length!!,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            //设置第二部分文本的字体大小和颜色
            spannableString.setSpan(
                AbsoluteSizeSpan(textSize2.toInt()),
                textContent1.length,
                textContent1.length + textContent2?.length!!,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(textColor2),
                textContent1.length,
                textContent1.length + textContent2.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            //设置第三部分文本的字体大小和颜色
            spannableString.setSpan(
                AbsoluteSizeSpan(textSize3.toInt()),
                textContent1.length + textContent2.length,
                spannableString.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(textColor3),
                textContent1.length + textContent2.length,
                spannableString.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            text = spannableString
            a.recycle()
        }
    }

    fun setSizeColorData(datas: ArrayList<ColorSizeData>) {
        val sbContent = StringBuilder()
        datas.forEachIndexed { index, colorSizeData ->
            sbContent.append(colorSizeData.content)
        }
        // 创建一个SpannableString对象
        val spannableString = SpannableString(sbContent.toString())
        var startIndex = 0
        var endIndex = 0

//        for (index in 0 until datas.size) {
//            endIndex += datas[index].content?.length!!
//            if (index > 0) {
//                startIndex += datas[index - 1].content?.length!!
//            }
//            Log.e("ColorSizeTextView:", "$startIndex,$endIndex")
//        }

        for (index in 0 until datas.size) {
            endIndex += datas[index].content?.length!!
            if (index > 0) {
                startIndex += datas[index - 1].content?.length!!
            }
            Log.e("ColorSizeTextView:", "$startIndex,$endIndex")
            Log.e("ColorSizeTextView---size:", "${datas[index].textSize}")
            // 设置第一部分文本的字体大小和颜色
            spannableString.setSpan(
                AbsoluteSizeSpan(datas[index].textSize),
                startIndex,
                endIndex,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(datas[index].textColor),
                startIndex,
                endIndex,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        text = spannableString
    }

    class ColorSizeData(
        var textColor: Int,
        var textSize: Int,
        var content: String?
    )
}

  2.用法

tvContent.setSizeColorData(ArrayList<ColorSizeTextView.ColorSizeData>().apply {
            add(
                ColorSizeTextView.ColorSizeData(
                    Color.parseColor("#3700B3"),
                    PxUtils.sp2px(this@TextViewDifferentColorAndSizeActivity,14f),
                    "德玛西亚啊"
                )
            )
            add(
                ColorSizeTextView.ColorSizeData(
                    Color.parseColor("#FF7201"),
                    PxUtils.sp2px(this@TextViewDifferentColorAndSizeActivity,12f),
                    "诺克萨斯33333333333333333"
                )
            )
            add(
                ColorSizeTextView.ColorSizeData(
                    Color.parseColor("#333333"),
                    PxUtils.sp2px(this@TextViewDifferentColorAndSizeActivity,10f),
                    "光辉女郎寒冰射手牛逼库拉斯"
                )
            )
        })

 

posted on 2024-07-23 09:50  飘杨......  阅读(8)  评论(0编辑  收藏  举报