Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getMeasuredHeight() of TextView with wrapped text

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?

like image 275
nhaarman Avatar asked Jan 17 '13 19:01

nhaarman


1 Answers

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.

like image 198
Leonidos Avatar answered Oct 06 '22 09:10

Leonidos