直播软件开发,TextView内容过多,超过n行显示“...全文”
/**
* TextView超过两行,末尾显示"...全文"
* 为避免抖动,需在xml中设置TextView的maxHeight
* @param maxLine 最多几行
* @param strNum 末尾显示字符数
* @param str 末尾显示字符
*/
open fun setOnGlobalLayout(
it: TextView,
maxLine: Int = 2,
strNum: Int = 3,
str: String = "...<font color='#212126'> 全文</font>"
) {
val observer = it.viewTreeObserver
observer.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (it.width > 0 && it.height > 0) {
it.visibility = View.VISIBLE
if (observer.isAlive) {
//判断ViewTreeObserver 是否alive,如果存活的话移除这个观察者
it.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
if (it.lineCount > maxLine) {
val html1: String =
it.text.toString().subSequence(0, it.layout.getLineEnd(maxLine - 1) - strNum).toString()
it.text = fromHtml(html1 + str)
}
}
}
})
}
private fun fromHtml(source: String?): Spanned? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(source)
}
}
注意 :为避免抖动,需在xml中设置TextView的maxHeight
<TextView
android:id="@+id/tv_content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxHeight="@dimen/dp_40"
.../>
以上就是直播软件开发,TextView内容过多,超过n行显示“...全文”, 更多内容欢迎关注之后的文章
标签:...,软件开发,android,maxLine,全文,TextView,fromHtml From: https://www.cnblogs.com/yunbaomengnan/p/17522767.html