获取一个TextView的高度 [英] Get the height of a TextView

查看:278
本文介绍了获取一个TextView的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文字,将被放在一个的TextView 。我这样做,使用的setText()

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

现在我需要找到在的TextView 文本所占用的线路或高度数。我试图用的getHeight(),但它总是返回0。

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.

反正是有得到的文本present在高度的TextView

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

推荐答案

正如约翰指出,你将不能够的setText后立即得到高度。我不知道用在TextView的本身的getHeight()会帮助你很多。该视图的高度,不仅取决于在视图中可见文本的高度,但也对的ViewGroup /布局TextView的所在。如果在的ViewGroup告诉TextView的最大化高度,getHeight()都会将让你无处甚至如果你等待的文本渲染之后。

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. TextView的子类,并覆盖onSizeChanged方法。在那里,调用超onSizeChanged,然后得到由getLineCount TextView的内的行数(),每行的高度与getLineHeight()。这可能会或可能不会比使用的getHeight(),这取决于你的布局或诸如此类的东西更好。
  2. 不要使用Textviews尺寸。得到TextViews油漆与TextView.getPaint(),然后计算从

  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

矩形边界; paint.getTextBounds(文字,0,text.length(),边界);

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

现在,您将有边界的尺寸。现在,您可以用paint.breakText工作,看看有多少文字,你会放在一行。也许太多的麻烦,并且不保证(我的未经训练的眼睛)是所使用的TextView的相同的逻辑。

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.

这篇关于获取一个TextView的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆