我找到了一种从TypeFace
创建TypeFaceSpan
的方法,如下所示:
fun getTypeFaceSpan(typeFace:TypeFace) = TypeFaceSpan(typeFace)
但是这个API只 允许在API level >= 28使用。是否有任何兼容库可以实现低于28级的功能?
我找到了一种从TypeFace
创建TypeFaceSpan
的方法,如下所示:
fun getTypeFaceSpan(typeFace:TypeFace) = TypeFaceSpan(typeFace)
但是这个API只 允许在API level >= 28使用。是否有任何兼容库可以实现低于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()