【问题标题】:Android TextView does not hug text tightly with multiple lines, sticks to maxWidth insteadAndroid TextView 不会用多行紧紧地拥抱文本,而是坚持使用 maxWidth
【发布时间】:2023-03-11 22:05:02
【问题描述】:

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

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

【问题讨论】:

    标签: android textview word-wrap android-wrap-content


    【解决方案1】:

    事实证明,通过继承 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());
        }
    }
    

    【讨论】:

      【解决方案2】:

      在 TextView XML 中,你可以使用:

      android:justificationMode="inter_word"
      

      【讨论】:

      • 这确实让它看起来更糟。我已经用屏幕截图更新了我的帖子以说明原因。
      猜你喜欢
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多