使用自定义的LineHeightSpan替代lineSpacing小于1时的LineSpacingSpan。
示例代码如下:
class CustomLineHeightSpan(private val height: Int) : LineHeightSpan {
override fun chooseHeight(
text: CharSequence?,
start: Int,
end: Int,
spanstartv: Int,
v: Int,
fm: Paint.FontMetricsInt?
) {
if (fm != null) {
val lineHeight = fm.bottom - fm.top
if (lineHeight < height) {
val delta = (height - lineHeight) / 2
fm.top -= delta
fm.ascent -= delta
fm.bottom += delta
fm.descent += delta
}
}
}
}
// 可以在代码中设置TextView的行高
textView.setLineSpacing(0f, 1.5f)
// 在设置 SpannableString 时使用自定义的 LineHeightSpan
val spannableString = SpannableString("This is a text with background color")
val backgroundColorSpan = BackgroundColorSpan(Color.RED)
val lineHeightSpan =
CustomLineHeightSpan((textView.textSize * (1 + 1.5f)).toInt())
spannableString.setSpan(
backgroundColorSpan,
5,
10,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
spannableString.setSpan(
lineHeightSpan,
5,
10,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
下一篇:Android的本地调试