[英]Spannable String Builder not applying font
I'm trying to build a String that has two different custom fonts applied to it.我正在尝试构建一个应用了两种不同自定义字体的字符串。 I've appended the two strings with the respective font into a string builder, but this does nothing to the String at all?我已将带有相应字体的两个字符串附加到字符串构建器中,但这对字符串根本没有任何作用? Does anyone know why?有谁知道为什么?
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)
}
}
You can use this custom TypefaceSpan
class:您可以使用此自定义TypefaceSpan
类:
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
}
}
And apply that to your the SpannableStringBuilder
:并将其应用于您的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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.