我有一个设置为 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/