How to find the Text Area(Height/Width) of TextView programmatically in android

為{幸葍}努か 提交于 2019-11-28 09:05:50
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text,0,text.length(),bounds);
int height = bounds.height();
int width = bounds.width();

or

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

Please try this:

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());
}

Before you get width, you have to measure the view / label / text edit. Please let me know if this is not working.

Haresh Chhelana

Try this way,hope this will help you to solve your problem.

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

   }
});

please tell me width in??? do you want ?

TextView method getWidth() gives you width of your view, in pixels

TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels 
TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() *  txt.getLineHeight();
int width = txt.getWidth();

Well, I haven't converted this code into swift4 syntax, but the logic will remain the same. This is an extension method for Xamarin.ios(C#).

To Calculate the Height

 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;
    }

To Calculate the Width

    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;
    }

The logic here that will work for swift is

var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
        var estimatedSize = textView.SizeThatFits(size);
        var textViewFinalHeight = estimatedSize.Height;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!