从 SDK 版本 28 以下的 TypeFace 创建 TypeFaceSpan

Create TypeFaceSpan from TypeFace below SDK version 28

我找到了从 TypeFacecreate TypeFaceSpan 的方法,如下所示:

fun getTypeFaceSpan(typeFace:TypeFace) = TypeFaceSpan(typeFace)

但是这个API是允许的只在API级别>=28 。任何 Compat 库来实现这个 below 28

TypeFaceSpan是一个MetricAffectingSpan。所以即使没有任何确切的方法Span得到TypeFaceSpan,我们也可以CustomTypeFaceSpan 如下所示,用它代替 TypeFaceSpan.

class CustomTypefaceSpan(private val typeface: Typeface?) : MetricAffectingSpan() {
    override fun updateDrawState(paint: TextPaint) {
        paint.typeface = typeface
    }

    override fun updateMeasureState(paint: TextPaint) {
        paint.typeface = typeface
    }
}

并像这样使用它:

val typeFaceSpan = CustomTypefaceSpan(typeface)

灵感来自@erluxman 的答案并结合 Kotlin 的扩展功能:

fun Typeface.getTypefaceSpan(): MetricAffectingSpan {
    return if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.P) typefaceSpanCompatV28(this) else CustomTypefaceSpan(this)
}

@TargetApi(Build.VERSION_CODES.P)
private fun typefaceSpanCompatV28(typeface: Typeface) =
    TypefaceSpan(typeface)


private class CustomTypefaceSpan(private val typeface: Typeface?) : MetricAffectingSpan() {
    override fun updateDrawState(paint: TextPaint) {
        paint.typeface = typeface
    }

    override fun updateMeasureState(paint: TextPaint) {
        paint.typeface = typeface
    }
}

那么你可以这样使用它:

typeface.getTypefaceSpan()