2011-09-16 60 views
20

我有一个多行文本视图设置为android:layout_width="wrap_content",它呈现时,采用父级的所有可用宽度。当文本可以放在一行上时,wrap_content可以正常工作,但是在两行或更多行中,文本视图看起来与父宽度相匹配,从而在两侧留下看起来像填充的东西。为什么在多行TextView填充父项中包装内容?

由于文本不能放在一行上,文本视图是否假定要求所有可用宽度?我希望视图能够以最小的可能尺寸为界。

任何想法?

供参考,在这里是布局定义:

<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" 
/> 
+0

最小可能的宽度将最有可能几乎每行一个字...是你想要实现的吗? – BrainCrash

+0

文本解析和包装很好,但我说要添加一个背景颜色,我会看到视图的宽度扩展到父级的宽度,在文本的任一侧留下了各种填充。单行文本不会这样做,但是一旦文本换行,它似乎假定它需要所有可用宽度。解析后,以某种方式将视图重新布局并测量以包装内容会很好。 – Chase

+0

@Chase:我有同样的问题,这里的答案没有解决它。你能解决它吗?在这里看到我的问题:http://stackoverflow.com/questions/22970783/correct-textview-padding – oat

回答

38

我有同样的问题也... 您可以使用自定义的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; 
} 
} 
+0

这应该被标记为答案。 – sidon

+0

这完全是正确的答案。谢谢! – Tomasz

+0

@Vitaliy Polchuk:你可以看看类似的问题在这里:http://stackoverflow.com/questions/22970783/correct-textview-padding – oat

0

上面接受的答案一点点优化的解决方案:

@Override 
protected void onMeasure(int widthSpec, int heightSpec) { 
    int widthMode = MeasureSpec.getMode(widthSpec); 

    // if wrap_content 
    if (widthMode == MeasureSpec.AT_MOST) { 
     Layout layout = getLayout(); 
     if (layout != null) { 
      int maxWidth = (int) Math.ceil(getMaxLineWidth(layout)) + 
          getCompoundPaddingLeft() + getCompoundPaddingRight(); 
      widthSpec = MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST); 
     } 
    } 
    super.onMeasure(widthSpec, heightSpec); 
}