使用的AutoSize进行屏幕适配 如不需要可自行替换
/**
* 设置TextView段落间距 未处理间距问题,如若需要可以在计算高度自行处理
*
* @param tv 给谁设置段距,就传谁
* @param text 文字内容
* @param paragraphHeight 段距
*/
private fun setParagraphSpacing(
tv: TextView,
text: String,
paragraph:Float
) {
if (!text.contains("\n")) {
tv.text = text
return
}
var content = text
content = content.replace("\n", "\n\r")
var previousIndex = content.indexOf("\n\r")
//记录每个段落开始的index,第一段没有,从第二段开始
val nextParagraphBeginIndexes: MutableList<Int> = ArrayList()
nextParagraphBeginIndexes.add(previousIndex)
while (previousIndex != -1) {
val nextIndex = content.indexOf("\n\r", previousIndex + 2)
previousIndex = nextIndex
if (previousIndex != -1) {
nextParagraphBeginIndexes.add(previousIndex)
}
}
//把\r替换成透明长方形(宽:1px,高:字高+段距)
val spanString = SpannableString(content)
val d = ContextCompat.getDrawable(context, R.drawable.paragraph_space)
//计算加上段落的高度 :行高 + 段距
d!!.setBounds(
0,
0,
1,
(tv.lineHeight + AutoSizeUtils.dp2px(context, paragraphHeight))
)
for (index in nextParagraphBeginIndexes) {
// \r在String中占一个index
spanString.setSpan(
ImageSpan(d),
index + 1, index + 2,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
tv.text = spanString
}