我将多行文本视图设置为android:layout_width="wrap_content"
当渲染时,它会占用父级的所有可用宽度。当文本可以容纳在一行中时,wrap_content
工作正常,但在两行或更多行时,文本视图似乎与父级宽度相匹配,在两侧留下看起来像填充的内容。
由于文本无法容纳在一行中,因此文本视图是否假设需要所有可用宽度?我希望视图受到尽可能小的尺寸的限制。
有任何想法吗?
作为参考,这里是布局定义:
<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"
/>
我也遇到了同样的问题...
您可以使用自定义 TextView 和重写方法 onMeasure() 来计算宽度:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)