Find programmatically generated TextView's height

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.

android
asked on Stack Overflow Mar 24, 2014 by shadowarcher • edited Jan 4, 2019 by Cœur

2 Answers

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);
answered on Stack Overflow Mar 24, 2014 by dharms
0

You can do

yourView.getLayoutParams().height
answered on Stack Overflow Mar 24, 2014 by Guillermo Merino

User contributions licensed under CC BY-SA 3.0