getWidth()和getMeasuredWidth()的区别

文章出自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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值