I'm trying to determine the height of a TextView
before it is drawn. I'm using the following code to do that:
TextView textView = (TextView) findViewById(R.id.textview);
textView.setText("TEST");
int widthSpec = MeasureSpec.makeMeasureSpec(LayoutParams.MATCH_PARENT, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
textView.measure(widthSpec, heightSpec);
System.out.println("MeasuredHeight: " + textView.getMeasuredHeight());
The output is MeasuredHeight: 28
. Nothing wrong with that.
However, when I give the TextView
a long text string, so wrapping occurs, it still gives the height of a single line instead of two:
(...)
textView.setText("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST");
(...)
The output is MeasuredHeight: 28
, where I would expect MeasuredHeight: 56
.
Why doesn't it give me the right value and how can I achieve the right value?
This is a onCreate method. Your whole view hierarchy isn't measured and layouted yet. So textView's parent doesn't know it's width. That is why textView's dimentions isn't constrained by it's parent's dimentions.
Try to change your line to:
int widthSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
so it make your textview width equals 200 pixels.
If you explain why do you need textview's height maybe we will be able to help you.
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