0

I need help finding out the height of a TextView after I create it programmatically. I generate a TextView like this:

public TextView drawTextView(String text, boolean center, boolean bold, int topMargin, int leftMargin, int textSize) {
    View vt = new TextView(getBaseContext());
    final TextView textView = new AutoResizeTextView(vt.getContext());

    Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/GothamMedium.ttf");

    textView.setText(text);
    textView.setTextColor(0xFFFFFFFF);
    if (bold) {
        textView.setTypeface(tf, Typeface.BOLD);
    } else {
        textView.setTypeface(tf);
    }
    if (center) {
        textView.setGravity(Gravity.CENTER);
    }
    textView.setTextSize(textSize);
    textView.setSingleLine(false);

    LayoutParams paramsText = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    paramsText.leftMargin = leftMargin;
    paramsText.topMargin = topMargin;

    container.addView(textView, paramsText);

    return textView;
  }

What I'd like to be able to do is something like this:

TextView text = drawTextView(map.get("business"), false, true, topMargin, 30, 40);

topMargin += text.getHeight() + 5;

text = drawTextView(map.get("text"), false, true, topMargin, 30, 16);

topMargin += text.getHeight() + 5;

text = drawTextView(map.get("detail"), false, false, topMargin, 30, 16);

topMargin += text.getHeight() + 5;

So that I know that the text from different TextViews isn't going to overlap, there will always be a 5 pixel difference even if the text ends up being taller than just one line of text, and in order to account for different TextView sizes on different phones. However text.getHeight() always just returns 0. Is there anything I can do to fix this, I've been looking all over for a solution but I haven't found one.

Cœur
  • 37,241
  • 25
  • 195
  • 267
shadowarcher
  • 3,265
  • 5
  • 21
  • 33
  • If a view hasn't been layed out (drawn) yet, its width and height are 0. For example, in onCreate() method of an activity views aren't drawn yet. So, you should use view's height when the view itself is layed out, for example, in onGlobalLayout() method of OnGlobalLayoutListener. Some can be found [here](http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r?rq=1) – Onik Mar 24 '14 at 18:10

2 Answers2

0

Rather than manually drawing at absolute positions, I would suggest using a vertical LinearLayout. You can set the top margin of each TextView to be 5 pixels. It could look something like this:

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.textContainer); //Or make one programmatically
TextView textView = ...; //Your creation code from above plus layout params with 5 pixel top margin
linearLayout.addView(textView);
Dan Harms
  • 4,725
  • 2
  • 18
  • 28
0

You can do

yourView.getLayoutParams().height
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34