Spannable String Builder 未应用字体

Spannable String Builder not applying font

我正在尝试构建一个应用了两种不同自定义字体的字符串。我已经将带有相应字体的两个字符串附加到一个字符串生成器中,但这对字符串根本没有任何作用吗?有谁知道为什么?

private fun createSpannedNameAndComment(name: String, comment: String): SpannableStringBuilder {

    val semiBoldFont = android.graphics.Typeface.create(
        ResourcesCompat.getFont(
            this,
            R.font.josefin_san_semi_bold
        ), android.graphics.Typeface.NORMAL
    )

    val regularFont = android.graphics.Typeface.create(
        ResourcesCompat.getFont(
            this,
            R.font.josefin_san_regular
        ), android.graphics.Typeface.NORMAL
    )

    return SpannableStringBuilder().apply {
        append(name, semiBoldFont, 0)
        append(" ")
        append(comment, regularFont, 0)
    }

}

你可以使用这个自定义 TypefaceSpan class:

class CustomTypefaceSpan constructor(type: Typeface) : TypefaceSpan("") {

    private var newType = type

    override fun updateDrawState(ds: TextPaint) {
        applyCustomTypeFace(ds, newType)
    }

    override fun updateMeasureState(paint: TextPaint) {
        applyCustomTypeFace(paint, newType)
    }

    private fun applyCustomTypeFace(paint: Paint, tf: Typeface?) {
        val old: Typeface = paint.typeface
        val oldStyle = old.style
        val fake = oldStyle and tf!!.style.inv()
        if (fake and Typeface.BOLD != 0) paint.isFakeBoldText = true
        if (fake and Typeface.ITALIC != 0) paint.textSkewX = -0.25f
        paint.typeface = tf
    }

}

并将其应用到您的 SpannableStringBuilder:

private fun createSpannedNameAndComment(name: String, comment: String): SpannableStringBuilder {

    val semiBoldFont = android.graphics.Typeface.create(
        ResourcesCompat.getFont(
            this,
            R.font.josefin_san_semi_bold
        ), android.graphics.Typeface.NORMAL
    )

    val regularFont = android.graphics.Typeface.create(
        ResourcesCompat.getFont(
            this,
            R.font.josefin_san_regular
        ), android.graphics.Typeface.NORMAL
    )

    return SpannableStringBuilder().apply {
        append(name, CustomTypefaceSpan(semiBoldFont), 0)
        append(" ")
        append(comment, CustomTypefaceSpan(regularFont), 0)
    }

}