如何在android中以编程方式查找TextView的文本区域(高度/宽度)

时间:2014-06-23 06:20:24

标签: android android-layout textview layoutparams

我有一个EditText,一个Button和一个TextView。单击该按钮时,textview显示以edittext编写的文本。是否可以根据文本找到占用的textview的大小。即如果它有三个字符" abc ",现在宽度是多少,如果它有5个字符,如" abcde "那么宽度是多少?

6 个答案:

答案 0 :(得分:60)

Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text,0,text.length(),bounds);
int height = bounds.height();
int width = bounds.width();

textView.setText("bla");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();

答案 1 :(得分:10)

请试试这个:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView edit = (TextView) findViewById(R.id.edit);
    edit.setTextSize(20);       
    edit.setText("Hello, world");       
    edit.measure(0, 0);
    int width = edit.getMeasuredWidth();
    Log.w("width", width.toString());
}

在获得宽度之前,您必须测量视图/标签/文本编辑。 如果这不起作用,请告诉我。

答案 2 :(得分:2)

试试这种方式,希望这可以帮助您解决问题。

yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
     int width = yourTextView.getMeasuredWidth();
     int height = yourTextView.getMeasuredHeight();

   }
});

答案 3 :(得分:2)

请告诉我宽度???你想要吗?

TextView方法getWidth()为您提供视图的宽度(以像素为单位)

TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels 

答案 4 :(得分:1)

TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() *  txt.getLineHeight();
int width = txt.getWidth();

答案 5 :(得分:0)

嗯,我还没有将此代码转换为swift4语法,但是逻辑将保持不变。这是Xamarin.ios(C#)的扩展方法。

计算高度

 public static nfloat GetEstimateHeight(this UITextView textView, UIView View)
    {
        var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
        var estimatedSize = textView.SizeThatFits(size);
        return estimatedSize.Height;
    }

计算宽度

    public static nfloat GetEstimateWidth(this UITextView textView, UIView View)
    {
        var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
        var estimatedSize = textView.SizeThatFits(size);
        return estimatedSize.Width;
    }

这里适用于迅速的逻辑是

var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
        var estimatedSize = textView.SizeThatFits(size);
        var textViewFinalHeight = estimatedSize.Height;