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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With