0

我正在创建一个聊天气泡,我注意到当您有一个 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"

导致文本适合框而不是框适合文本,这更难看:

inter_word t

4

2 回答 2

0

事实证明,通过继承 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());
    }
}
于 2021-05-04T20:36:10.727 回答
-1

在 TextView XML 中,您可以使用:

android:justificationMode="inter_word"
于 2021-04-21T09:44:01.463 回答