贴出kotlin代码,复写一个新的Textview,重写onmeasure的方法.同时xml里面Textview设置android:ellipsize="end"
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var layout: StaticLayout? = null
var field: Field? = null
try {
val staticField = DynamicLayout::class.java!!.getDeclaredField("sStaticLayout")
staticField.setAccessible(true)
layout = staticField.get(DynamicLayout::class.java) as StaticLayout
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
if (layout != null) {
try {
field = StaticLayout::class.java!!.getDeclaredField("mMaximumVisibleLineCount")
field!!.isAccessible = true
field.setInt(layout, maxLines)
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (layout != null && field != null) {
try {
field.setInt(layout, Integer.MAX_VALUE)
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
}
最后完美解决:如图所示

相关文章: