如何知道组件在其父组件中可以采用的大小?
我正在创建一个自定义组件,我在哪里可以知道它的父组件可以采用的尺寸?在布局中,它是用 fill_parent x fill_parent 定义的。
我在构造函数、 onMeasure 方法和 onFinishInflate 上尝试了 getWidth() x getHeight() ,在所有情况下都返回 0,我希望知道以独立屏幕尺寸绘制某些组件所需的尺寸。
I'm creating a custom component, where can I know the dimensions this can assume on it's parent? In Layout it's defined with fill_parent x fill_parent.
I tried getWidth() x getHeight() on the constructor, on the onMeasure method and onFinishInflate, in all cases this return 0, I wish to know the size it's have to draw some components in independent screen size.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以重写 onMeasure() 并从那里获取值。
http://developer.android.com/参考/android/view/View.html#onMeasure(int, int)
在 onMeasure 中,您实际上可以为组件设置自己的尺寸,并根据尺寸构建组件。
使用 View.MeasureSpec.getSize(方法接受的参数之一。宽度或高度)来获取尺寸。
You can override onMeasure() and get values from there.
http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)
In onMeasure you can actually set your own dimensions for the component and build component accordingly to sizes after that.
Use View.MeasureSpec.getSize(one of the parameters methods takes in. Either width, or height) to get dimensions.
getWidth()
和getHeight()
只会在布局阶段之后填充,即在调用onLayout()
之后。您不应使用
onMeasure()
或getMeasuredWidth()
/getMeasuredHeight()
中的值,因为这些只是 View 最初的尺寸提供或想要拥有的,不一定是最终实际得到的。请参阅http://developer.android.com/guide/topics/ ui/how-android-draws.html 了解更多信息。
getWidth()
andgetHeight()
will only be populated after the Layout Phase, that is afteronLayout()
has been called.You should not use the values within
onMeasure()
orgetMeasuredWidth()
/getMeasuredHeight()
, since those are only the dimensions the View is initially offered or would like to have, not necessarily the ones it actually ends up getting.See http://developer.android.com/guide/topics/ui/how-android-draws.html for more information.