Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the width of textView in android

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.

like image 523
AMIT Avatar asked Apr 03 '14 10:04

AMIT


2 Answers

Try like this:

textView.setText("GetHeight");
textView.measure(0, 0);       //must call measure!
textView.getMeasuredHeight(); //get height
textView.getMeasuredWidth();  //get width
like image 136
Lokesh Avatar answered Nov 19 '22 15:11

Lokesh


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

    });
like image 5
Chinmoy Debnath Avatar answered Nov 19 '22 14:11

Chinmoy Debnath