简体   繁体   中英

Get the height of a TextView

I have some text that will be put in a TextView . I did that using setText() .

Now I need to find the number of lines or height the text occupies in the TextView . I tried using getHeight() , but it always returns 0.

Is there anyway to get the height of the text present in the TextView ?

Because this size is known only after the layout is finished, one way is to create a custom text view and use onSizeChanged method. Another way is this:

    final TextView tv = (TextView) findViewById(R.id.myTextView);
    ViewTreeObserver vto = tv.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            Toast.makeText(MyActivity.this, tv.getWidth() + " x " + tv.getHeight(), Toast.LENGTH_LONG).show();
            tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } 
    }); 

This code I've found here: How to retrieve the dimensions of a view?

As John pointed out, you won't be able to get the height immediately after setText. I'm not sure using getHeight() on the TextView itself will help you much. The height of the view is not only dependant on the height of the visible text in the view, but also on the viewgroup/layout the TextView resides in. If the viewgroup tells the TextView to maximize height, getHeight() will get you nowhere even if you wait until after the text is rendered.

I see a number of ways that this could be done:

  1. Subclass TextView and overwrite the onSizeChanged method. In there, call supers onSizeChanged, then get the number of lines within the TextView by getLineCount() and the height per line with getLineHeight(). This might or might not be better than using getHeight(), depending on your layout or whatnot.
  2. Don't use the Textviews dimensions. Get the TextViews Paint with TextView.getPaint(), and then calculate the width and height from

    Rect bounds; paint.getTextBounds(text, 0, text.length(), bounds);

You'll now have the dimensions in bounds. You can now work with paint.breakText to see how much text you'll fit on one line. Probably too much hassle and not guaranteed (to my untrained eye) to be the same logic as used by TextView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM