0
点赞
收藏
分享

微信扫一扫

TextView内容过多,超过n行显示“...全文”

四月Ren间 2022-03-25 阅读 36

TextView内容过多,超过n行显示“...全文”,“查看全文”等

一、需求图片

内容超过两行时,在末尾显示“… 全文”
在这里插入图片描述

二、上代码

	/**
     * TextView超过n行,末尾显示"... 全文"
     * 为避免抖动,需在xml中设置TextView的maxHeight
     */
    private val n: Int = 2  //第二行
    private val str: String = "...<font color='#212126'> 全文</font>"  //末尾显示"... 全文",加强颜色
    open fun setOnGlobalLayout(it: TextView) {
        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 > n) {
                        val html1: String = it.text.toString().subSequence(0, it.layout.getLineEnd(1) - 3).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"
    .../>

三、其他需求

点击 “全文”,在列表中展开全文,后续补上。。。

写在最后
此文章为个人开发时记录,有时时间有限,无法深入研究,若看到此文章后有其他见解或解决方式,欢迎留言交流👇👇👇

————————————————

举报

相关推荐

0 条评论