获取TextView中文本的大小
我在将 textView 放置在指定中心的 x 和 y 坐标时遇到问题。 首先,我尝试在textView中设置文本,并用视图的宽度和高度移动视图 通过此链接。
但这不起作用,我想尝试其他方法。 我想知道是否有一种方法可以获取指定文本在我的textView中所采用的大小? 我的意思是,我知道文本和textSize,我怎样才能获得textView 将采用的宽度和高度?
对于那些了解 iPhone 开发的人来说,类似于方法 (NSString)sizeWithFont;
。
I have a problem placing a textView at specified center's x and y coordinates.
Firstly, I tried to set the text in the textView, and to move the view with the width and the height of the view
from this link.
But it doesn't work, and I'd like to try something else.
I'd like to know if there is a method to get the size which a specified text will take in my textView?
I mean, I know the text and the textSize, how can I get the width and the height my textView will take?
Something like the method (NSString)sizeWithFont;
for those who know iPhone dev.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
bounds.width()
将为您提供文本视图中文本的准确宽度。bounds.width()
will give you the accurate width of the text in the Text View.如果您的 textview 称为 tv
更多信息(已更新): 如何获取视图的宽度/高度
If your textview is called tv
More on this (updated): How to get width/height of a View
由于某种原因,Midverse Engineer 的解决方案并不总是给我正确的结果(至少在某些 Android 版本上)。 Sherif elKhatib 的解决方案有效,但具有更改 MeasuredWidth 和 Height 的副作用。这可能会导致 textView 定位不正确。
我的解决方案:
For some reason the solution of Midverse Engineer does not give me always correct results (at least on some Android versions). The solution of Sherif elKhatib works, but has the side effect of changing MeasuredWidth and Height. This could lead to incorrect positioning of the textView.
My solution:
当您有多行文本和不同的填充时,使用 TextView 内部
Paing
类并不是那么热门。因此,不要再尝试重新发明轮子了。调用measure(UNSPECIFIED, UNSPECIFIED)
后使用getMeasuredHeight
和getMeasuredWidth
方法。只是不要忘记在帖子中获取新值,否则大多数情况下您会得到错误的结果。Using the TextView inner
Paing
class is not so hot when you have multiple lines of text and different paddings. So stop trying to reinvent the wheel. UsegetMeasuredHeight
andgetMeasuredWidth
methods after callingmeasure(UNSPECIFIED, UNSPECIFIED)
. Just don't forget to get the new values inside the post, otherwise mostly you'll get a wrong result.