Question

I have initialised a TextView in code (that is, not initialised it from the layout)

TextView   v   =    new TextView(getApplicationContext());

Then I set the text

v.setText("Foo");

Then I try to get the height of this TextView

int i = v.getHeight();

This is giving 0.

Please advise

Was it helpful?

Solution

It's possible that your TextView isn't measured yet. With a ViewTreeObserver you can be notify when your TextView is rendered, then you can have it's height :

ViewTreeObserver vto = v.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
if (v != null && getActivity() != null) {
    ViewTreeObserver obs = v.getViewTreeObserver();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        obs.removeOnGlobalLayoutListener(this);
    } else {
        obs.removeGlobalOnLayoutListener(this);
    }
    int i = v.getHeight();

    }
 }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top