Android 富文本拼接工具

有时一行文字需要设置不同大小、颜色、等甚至字体时,我们可以使用富文本来实现。本文暂只提供文本大小,颜色,字体,换行等操作的代码基类,如需其他,可按需自行实现。 

class SpannableUtils(private val textView: TextView) {

    val spanMode: Int = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    var enter: String? = System.getProperty("line.separator")
    var texts: ArrayList = ArrayList()

    var currentIndex: Int = -1

    fun append(@NotNull text: String): SpannableUtils {
        //打开这里可以让下一个span继承上一个字span的样式,但我感觉没什么必要
        //var initArray: ArrayList = ArrayList()
        //if (currentIndex >= 0) {
        //    initArray = texts[currentIndex].spans
        //}
        //texts.add(Spannable(text, initArray))
        texts.add(Spannable(text, ArrayList()))
        currentIndex++
        return this
    }

    fun appendLine(): SpannableUtils {
        if (enter == null) {
            enter = "\n"
        }
        return append(enter!!)
    }

    private fun addSpan(span: Any): SpannableUtils {
        texts[currentIndex].spans.add(span)
        return this
    }

    fun setTextColor(@ColorInt color: Int): SpannableUtils {
        return addSpan(ForegroundColorSpan(color))
    }

    fun setTextSize(size: Float): SpannableUtils {
        return addSpan(AbsoluteSizeSpan(DensityUtil.sp2px(size)))
    }

    fun setTypeface(typeface: Typeface): SpannableUtils {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            addSpan(TypefaceSpan(typeface))
        } else {
            addSpan(StyleSpan(typeface.style))
        }
    }

    fun create(): SpannableString {
        if (currentIndex == -1) {
            return SpannableString("")
        }
        var text = ""
        var length = 0
        texts.forEach {
            text += it.text
        }
        val spannableString = SpannableString(text)
        texts.forEach {
            val textLength = it.text.length
            it.spans.forEach {
                spannableString.setSpan(it, length, length + textLength, spanMode)
            }
            length += it.text.length
        }
        textView.text = spannableString
        return spannableString
    }

    class Spannable(var text: String = "", var spans: ArrayList = ArrayList())


}

你可能感兴趣的:(Android开发,android,kotlin,SpannableString)