getWidth()和getMeasuredWidth()的区别

来源:互联网 发布:rds sql审计 编辑:程序博客网 时间:2024/05/21 07:08

文章出自stackoverflow
我也是因为对这个问题搞不颠,所以才去找答案,找来找去发现国外的这个解释不错,于是转过来安利给大家。

As the name suggests the measuredWidth/height is used during measuring and layoutting phase.
Let me give an example,

A widget is asked to measure itself, The widget says that it wants to be 200px by 200px. This is measuredWidth/height.

During the layout phase, i.e. in onLayout method. The method can use the measuredWidth/height of its children or assign a new width/height by calling layout method of the view.

Lets say the onLayout method calls childview.layout(0,0,150,150) now the width/height of the view is different than the measured width/height.

I would suggest not to use the measuredWidth/height outside onLayout method.

to summarize:

onMeasure -> sets up measuredWidth/measuredHeight
onLayout -> sets up the width/height of the widget.

additionallly

public void View.layout(int l, int t, int r, int b)

seems to be place where the assignment of position and size happens.

Q:that is , we should always use getWidth/getHeight to get the “real” dimension of a View, right?
A:Yes, but if you are doing your own layouting then you should use measuredWidth instead of width.
Q:So, what’s the purpose of setting dimesions inside onMeasure()? I mean, the layout pass is the last one, in which you set the final dimensions of the view, possibliy regardless of measured dimensions
A:@edoardotognoni it depends upto the layout (LinearLayout, RelativeLayout or your custom layout) , to give the correct size and position to the view.
Q:Ok let’s say the view tells “I’d like these dimensions”. While the layout says “You will have these dimensions”. Is it right?

突然觉得太简单了,不(周)想(五)翻(下)译(班)。
O(∩_∩)O~

0 0
原创粉丝点击