简体   繁体   中英

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.

Try like this:

textView.setText("GetHeight");
textView.measure(0, 0);       //must call measure!
textView.getMeasuredHeight(); //get height
textView.getMeasuredWidth();  //get width

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

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM