问题描述
我正在创建一个聊天气泡,我注意到当你有一个文本跨多行的 TextView 时,框的宽度锁定到(在这种情况下)maxWidth。这可能会导致右侧出现间隙:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="100dp"
android:padding="4dp"
android:text="this is a pretty short sentence"/>
如您所见,右侧有一个很大的白色间隙。没有 maxWidth 它适合在一条线上并且紧贴:
如何使文本跨越多行时,框仍然紧紧地拥抱文本?我尝试了很多东西,但这可能吗?
预期结果:
更新:
android:justificationMode="inter_word"
导致文本适合框而不是框适合文本,这更丑:
解决方法
事实证明,通过继承 TextView 和覆盖 onMeasure() 很容易修复。它甚至适用于布局编辑器。性能也完全没有问题:
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
//call super first so you can call getLineCount(),getLineMax()) and getMeasuredHeight() below
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
//if more than 1 line set width equal to that of the largest line
int lineCount = getLayout().getLineCount();
if (lineCount > 1) {
//get the width of the largest line
float lineWidth = 0;
for (int i = 0; i < lineCount; i++) {
lineWidth = Math.max(lineWidth,getLayout().getLineMax(i));
}
//set largest line width + horizontal padding as width and keep the height the same
setMeasuredDimension((int) Math.ceil(lineWidth) + getPaddingLeft() + getPaddingRight(),getMeasuredHeight());
}
}
,
在 TextView XML 中,您可以使用:
android:justificationMode="inter_word"