Android kotlin 自定义TextView三行显示尾部添加全文字样
在 Android Kotlin 中,你可以自定义一个 TextView 来实现三行显示,并在尾部添加全文字样。
首先,你需要创建一个自定义的 TextView 类,代码如下:
import android.content.Context
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
class CustomTextView(context: Context, attrs: AttributeSet) : androidx.appcompat.widget.AppCompatTextView(context, attrs) {
private val ellipsis = "..."
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val textPaint = paint
val availableWidth = measuredWidth - paddingLeft - paddingRight
val maxLines = 3
if (lineCount > maxLines) {
val text = text.toString()
val layout = createStaticLayout(text, textPaint, availableWidth, maxLines)
val lastLineText = text.substring(layout.getLineStart(maxLines - 1))
val lastLineLayout = createStaticLayout(lastLineText + ellipsis, textPaint, availableWidth, 1)
val newHeight = layout.height + lastLineLayout.height
setMeasuredDimension(measuredWidth, newHeight)
}
}
private fun createStaticLayout(text: String, textPaint: TextPaint, width: Int, maxLines: Int): StaticLayout {
return StaticLayout.Builder
.obtain(text, 0, text.length, textPaint, width)
.setMaxLines(maxLines)
.setEllipsize(null)
.build()
}
}
然后,在你的布局文件中使用这个自定义的 TextView,代码如下:
<com.yourpackage.CustomTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="3"
android:text="Your text goes here..."
/>
通过设置 android:maxLines="3",你可以限制 TextView 只显示三行。当文本超过三行时,它将在尾部添加一个省略号。
希望对你有帮助
原文地址: https://www.cveoy.top/t/topic/iYq9 著作权归作者所有。请勿转载和采集!