TextView系统属性设置省略号后面间距大小不一致问题
android:ellipsize="end"
省略号后面的间距显示过宽,当在有限的宽度里面显示不下一个字符的时候,就会产生间距。
那么我们可以尝试去获取文本的真实宽度,重新设置文本的宽度。
自定义TextView重写onMeasure方法,通过layout.getLineWidth(0)获取文本第一行的宽度进行设置
class NoPaddingSingleLineTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : AppCompatTextView(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (layout.lineCount != 1) return
val lineWidth = layout.getLineWidth(0).toInt()
val viewWidth = measuredWidth
if (viewWidth <= 0) return
if (viewWidth == lineWidth) return
setMeasuredDimension(lineWidth, measuredHeight)
}
}
实现后的效果,省略号后面的间距消失了
<com.example.testdemo.NoPaddingSingleLineTextView
android:id="@+id/tv_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:singleLine="true"
android:ellipsize="end"
android:textStyle="bold"
android:layout_marginHorizontal="20dp"
android:textColor="@color/white"
android:background="#ff4438"/>
这种方案只针对单行文本并需要显示省略号的情况。