Kotlin 开发人员可以使用它为单个按钮或文本视图使用两个或多个字体。
1.复制粘贴这个类:
class CustomTypefaceSpan(family: String?, private val newType: Typeface) : TypefaceSpan(family) {
override fun updateDrawState(ds: TextPaint) {
applyCustomTypeFace(ds, newType)
}
override fun updateMeasureState(paint: TextPaint) {
applyCustomTypeFace(paint, newType)
}
companion object {
private fun applyCustomTypeFace(paint: Paint, tf: Typeface) {
val oldStyle: Int
val old = paint.typeface
oldStyle = old?.style ?: 0
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
}
}
}
2. 通过以下方式使用它:
val buttonText = "Get it for 100 Points"
//making text yellow
buttonText.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
this, R.color.yellow_FFC001
)
),
11, 14,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
//changing text size of yellow portion i.e. "100"
val sp20 = resources.getDimensionPixelSize(R.dimen.sp_20)
buttonText.setSpan(AbsoluteSizeSpan(sp20), 11, 14, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
//setting button fonts
buttonText.setSpan(
CustomTypefaceSpan("", ResourcesCompat.getFont(this, R.font.roboto_condensed_bold)!!),
0,
buttonText.length,
0
)
//finally setting this text to my button
btGetPoints.text = buttonText
3.最终的输出是这样的