Android:如何获取自定义View的高度和宽度?
如何使用 getMeasuredWidth()
和 getMeasuredHeight()
?它总是返回 0。这与 getHeight()
和 getWidth()
有什么区别?
How do I use getMeasuredWidth()
and getMeasuredHeight()
? It always returns 0. What is the difference between this and getHeight()
and getWidth()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
刚刚找到了一个获取自定义视图的高度和宽度的解决方案:
它适用于我的情况。
Just got a solution to get height and width of a custom view:
Its working in my case.
您可以使用以下方法获取视图的宽度和高度,
例如,
这给出了 XML 布局中指定的视图的转换值。
假设如果 XML 中指定的高度值为 53dp,则您将得到整数转换后的值为 80。
You can use the following method to get the width and height of the view,
For example,
This gives the converted value of the view which specified in the XML layout.
Say if the specified value for height is 53dp in XML, you will get the converted value in integer as 80.
不要尝试将它们放入其构造函数中。尝试在
onDraw()
方法中调用它们。Don't try to get them inside its constructor. Try Call them in
onDraw()
method.我还迷失了
getMeasuredWidth()
和getMeasuredHeight()
getHeight()
和getWidth()
很长一段时间时间......后来我发现onSizeChanged()
方法真的很有帮助。新博客文章:如何在 Android 中获取自定义视图(扩展视图)的宽度和高度尺寸 http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
I was also lost around
getMeasuredWidth()
andgetMeasuredHeight()
getHeight()
andgetWidth()
for a long time.......... later i foundonSizeChanged()
method to be REALLY helpful.New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
getHeight()
和getMeasuredHeight()
之间的区别在于,第一个方法将返回View
的实际高度,第二个方法将返回汇总高度View
的子级。换句话说,getHeight()
返回视图高度,getMeasuredHeight()
返回该视图需要显示其所有元素的高度The difference between
getHeight()
andgetMeasuredHeight()
is that first method will return actual height of theView
, the second one will return summary height ofView
's children. In ohter words,getHeight()
returns view height,getMeasuredHeight()
returns height which this view needs to show all it's elementsgetHeight
获取高度,getWidth
获取宽度。但你调用这些方法太早了。如果您在
onCreate
或onResume
中调用它们,则视图尚未绘制。您必须在绘制视图后调用它们。Well
getHeight
gets the height, andgetWidth
gets the width. But you're calling those methods too soon.If you're calling them in
onCreate
oronResume
, the view isn't drawn yet. You have to call them after the view has been drawn.