1

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

EdmDroid
  • 1,350
  • 1
  • 11
  • 25
  • 1
    `TextView v = new TextView(ActivityName.this));` and v should be added to root layout or to the activity. and read http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context although your `v.getHeight()` is a different problem – Raghunandan Jan 06 '14 at 13:28
  • You have just created the object, has the measure and layout pass happened ? How can you get height before that. Add it to some layout, then call v.requestLayout(), then call layout.post(new Runnable() { public void run() {mHeight = v.getHeight}};) Posted runnable would run after the measure/layout pass. Hope that helps. – himanshurb Jan 06 '14 at 13:33
  • Actually, a piece of information missing in my post.......I add the view to a table row and then call getHeight() on the TextView – EdmDroid Jan 06 '14 at 13:52

1 Answers1

0

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

    }
 }
});
Andros
  • 4,069
  • 1
  • 22
  • 30
  • Thanks but....this is too long. I have many TextViews added to the TableRow I mentioned in a comment in the post above. Any shorter method? – EdmDroid Jan 06 '14 at 13:56
  • Look at this interesting post on how to get the height of a view : http://www.sherif.mobi/2013/01/how-to-get-widthheight-of-view.html – Andros Jan 06 '14 at 14:03