如果您有一个带有 layout_width="wrap_content"
的 TextView 并且它必须换行到第二行以包含文本,那么它将调整其宽度以用尽所有可用空间(尊重边距等)。但是为什么在 View 的末尾有填充?我只是告诉它wrap_content,所以它应该包装那个内容!这似乎是一个错误,这在股票 Messenger 应用程序的聊天 UI 中可见。 (虽然图片来 self 自己的应用程序。但是那个额外的空间绝对不在 9 补丁中。)
任何解决方法?
更新:回复者/评论者没有捕获要点。也许我上传的图片具有误导性,因为它是从我的应用程序中设计的。任何 TextView 都会出现问题,您可以通过设置背景样式来查看 View 边界将不再紧张。我上传了不同的图片。这是图像中 TextView 的 XML:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:background="#dddddd"
android:text="This doesn't wrap"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_gravity="center_horizontal"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_gravity="center_horizontal"
android:background="#dddddd"
android:text="This wraps and look, the bounds does not fit tight against the right edge of text"
/>
最佳答案
我发现所选答案很有帮助,尽管它并没有完全考虑填充。我将所选答案与 this post's answer 结合在一起想出一个适用于填充的 View 。仅供引用,其他帖子的答案有一个缺陷,即 View 有时会在最后被截断几个像素。
public class TightTextView extends TextView {
public TightTextView(Context context) {
super(context);
}
public TightTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TightTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int specModeW = MeasureSpec.getMode(widthMeasureSpec);
if (specModeW != MeasureSpec.EXACTLY) {
Layout layout = getLayout();
if (layout != null) {
int w = (int) Math.ceil(getMaxLineWidth(layout)) + getCompoundPaddingLeft() + getCompoundPaddingRight();
if (w < getMeasuredWidth()) {
super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST),
heightMeasureSpec);
}
}
}
}
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/40800808/