0

In the layout, I have a textview with height wrap_content. The text size is 10 sp. So I want to know the exact height of the text.

The reason that I want to know the height is, I want to use image span to display some bitmap images in the text view. And the decode method needs the target width and height.

Is it possible? Thanks.

Jitesh Dalsaniya
  • 1,917
  • 3
  • 20
  • 36
XWang
  • 797
  • 2
  • 7
  • 20
  • TextView.getLayout().getHeight() – pskink Nov 02 '13 at 08:47
  • TextView.getLayout is not available when I try to get this in adapter's getView method. I think at that time that value is null. – XWang Nov 02 '13 at 13:40
  • what you mean "is not available" ? – pskink Nov 02 '13 at 14:10
  • ok, seems that layout phase is nor execured yet, you would need to run the code i posted before in a Runnable that you. pass to textview.post method – pskink Nov 02 '13 at 14:48
  • possible duplicate of [How do you to retrieve dimensions of a view? Getheight() and Getwidth() always return zero](http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r) – androidcodehunter Nov 03 '13 at 03:15

4 Answers4

0

You can get the heigth by the textview object:

    TextView text = (TextView) findViewById(R.id.<ID_OF_TEXTVIEW_IN_LAYOUT);
    int textViewHeigth = text.getHeigth();
André
  • 71
  • 2
  • 4
  • No, getHeight returns 0. getMeasuredHeight also returns 0. I call that method in adapter's getView function. – XWang Nov 02 '13 at 13:41
0

In activity onCreate() override onGlobalLayout method of your layout. This method is called after all views are computed. Get the textView height there.
Assuming that your TextView is in a RelativeLayout

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
relativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        relativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        TextView text = (TextView) findViewById(R.id.yourTextView);
        int textViewHeigth = text.getHeigth();

        //Do what you want
    }
});
ramaral
  • 6,149
  • 4
  • 34
  • 57
0

You can override onWindowFocusChanged method and here you can get the actual height and width of your view.

@Override
public void onWindowFocusChanged (boolean hasFocus) {
        // the height will be set at this point
        int textViewHeigth = text.getHeigth();
}

Here some post for you: getHeight returns 0 for all Android UI objects and another one How do you to retrieve dimensions of a view? Getheight() and Getwidth() always return zero

Community
  • 1
  • 1
androidcodehunter
  • 21,567
  • 19
  • 47
  • 70
0

There are two APIs in TextView which could be used. They are getTextSize and getLineHeight. Thanks for all the answer and help.

XWang
  • 797
  • 2
  • 7
  • 20