我找到了一种从TypeFace
create
TypeFaceSpan
的方法,如下所示:
fun getTypeFaceSpan(typeFace:TypeFace) = TypeFaceSpan(typeFace)
但此 API 仅在 API 级别>= 28 中允许。有没有兼容图书馆来实现低于 28 的这个目标?
TypeFaceSpan
是一个MetricAffectingSpan
。因此,即使没有任何确切的方法TypeFaceSpan
可以从 Span
,我们可以制作如下所示的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()