android - 为什么将内容包装在多行 TextView 填充父项中?

标签 android android-layout textview

我有一个设置为 android:layout_width="wrap_content" 的多行 TextView ,它在渲染时会占用父级的所有可用宽度。当文本可以放在一行时,wrap_content 工作正常,但在两行或多行时, TextView 似乎与父级宽度匹配,在两侧留下看起来像填充的东西。

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

有什么想法吗?

供引用,这是布局定义:

<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:

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;
}
}

关于android - 为什么将内容包装在多行 TextView 填充父项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439748/

相关文章:

安卓 : Centering Items in a ListVIew

安卓 Lollipop TextView : different vertical alignment of digits and letters

android - 如何使用我的 values/colors.xml 文件中定义的颜色更改 TextView 背景颜色?

android - 触摸/拖动特定 View 时禁用 viewpager

iphone - 为 iPhone 和 Android 开发 1 个移动应用程序时的 UI 设计

android.widget.SeekBar 无法转换为 android.widget.TextView

android - 在卡片 View 中对齐 TextView 下方的 TextView

android - 将按钮并排放置

android - 在 CardView 中显示 TextView

java - 我所有的布局 xml 文件都变成了自动生成的文件