27

This is the code what i am using...

<TextView
    android:id="@+id/textView"
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:text="AMIT KUMAR" />

and here is a java code.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = (TextView) findViewById(R.id.textView);
    Log.d("left", textView.getLeft() + " " + textView.getRight() + " "
            + textView.getWidth()+" "+textView.getHeight());
}

for all above i am getting the output 0.

so how can i get the width and height of textView.

InnocentKiller
  • 5,234
  • 7
  • 36
  • 84
AMIT
  • 390
  • 1
  • 4
  • 17

2 Answers2

93

Try like this:

textView.setText("GetHeight");
textView.measure(0, 0);       //must call measure!
textView.getMeasuredHeight(); //get height
textView.getMeasuredWidth();  //get width
drakeet
  • 2,685
  • 1
  • 23
  • 30
Lokesh
  • 5,180
  • 4
  • 27
  • 42
5

On your onCreate do this then you will get actual width and height of the textView

textView.postDelayed(new Runnable() {

            @Override
            public void run() {
                textView.invalidate();
                float dw = textView.getWidth();
                float dh = textView.getHeight();                
                Log.v("",dw + " - " + dh);              
            }
        }, 1);  

If you need to get width, height before view drawn then you can do this

ViewTreeObserver viewTreeObserver = textView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressLint("NewApi")
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            float dw = textView.getWidth();
            float dh = textView.getHeight();

            System.out.print(dw +" - "+dh);


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }

    });
Chinmoy Debnath
  • 2,814
  • 16
  • 20
  • ya i got the answer, but will you pls explain why you are using this code. means runnable thread – AMIT Apr 03 '14 at 10:47
  • The runnable doesn't get run until the layout has occurred. So it will wait until the view is displayed in screen and for this reason it will always gives correct width, height. But it will fail if you need to calculate width height before view drawn. – Chinmoy Debnath Apr 03 '14 at 10:55