为什么将内容包装在多行 TextView 填充父项中? [英] Why is wrap content in multiple line TextView filling parent?

查看:33
本文介绍了为什么将内容包装在多行 TextView 填充父项中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置为 android:layout_width="wrap_content" 的多行文本视图,它在呈现时会占用父级的所有可用宽度.当文本可以放在一行上时, wrap_content 工作正常,但在两行或更多行时,文本视图似乎与父宽度匹配,在任一侧留下看起来像填充的内容.

I have a multi line text view set to android:layout_width="wrap_content" that, when rendered, takes all available width of the parent. When the text can fit on one line, the wrap_content works fine, but at two or more lines, the text view seems to match the parents width, leaving what looks like padding on either side.

因为文本不能放在一行中,文本视图是否假设需要所有可用宽度?我希望视图以尽可能小的尺寸为界.

Because the text can not fit on one line, is the text view assuming to require all available width? I want the view to be bounded by the smallest possible dimensions.

有什么想法吗?

作为参考,这里是布局定义:

For reference, here is layout definition:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:singleLine="false"
    android:textSize="24sp"
    android:textStyle="bold"
    android:textColor="@color/white"
    android:gravity="center_horizontal"
/>

推荐答案

我也遇到了同样的问题...您可以使用带有覆盖方法 onMeasure() 的自定义 TextView 来计算宽度:

I had the same problem also... You may use custom TextView with overridden method onMeasure() where you calculate the width:

public class WrapWidthTextView extends TextView {

...

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    Layout layout = getLayout();
    if (layout != null) {
        int width = (int) Math.ceil(getMaxLineWidth(layout))
                + getCompoundPaddingLeft() + getCompoundPaddingRight();
        int height = getMeasuredHeight();            
        setMeasuredDimension(width, height);
    }
}

private float getMaxLineWidth(Layout layout) {
    float max_width = 0.0f;
    int lines = layout.getLineCount();
    for (int i = 0; i < lines; i++) {
        if (layout.getLineWidth(i) > max_width) {
            max_width = layout.getLineWidth(i);
        }
    }
    return max_width;
}
}

这篇关于为什么将内容包装在多行 TextView 填充父项中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆