onMeasure和onLayout

本文详细解析了Android中View与ViewGroup的核心方法onMeasure和onLayout的工作原理及调用流程,介绍了它们如何确定视图的尺寸和位置,并强调了在自定义View时正确使用这些方法的重要性。

可以参照View.java中

Implementing a Custom View

的介绍

1. onMeasure: determine the size requirements for this view and all of its children.

a. 属于View的方法,用来测量自己及其子元素来确定宽度和高度

b. view的measure方法体中会调用onMeasure

c. onMeasure中必须确定 measured width and height of this view, 调用 setMeasuredDimension(int, int)或者onMeasure(int, int)

CONTRACT: When overriding this method, you must callsetMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger anIllegalStateException, thrown bymeasure(int, int). Calling the superclass'onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should overrideonMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() andgetSuggestedMinimumWidth()).



2. onLayout:when this view should assign a size and position to all of its children

a. 属于ViewGroup的方法,用来为当前ViewGroup的子元素的位置和大小(大小是layout分配给本元素的显示空间大小,与本元素的大小可能不一样)

b. View的layout方法体中会调用onLayout


3.onMeasure和onLayout

onMeasure在onLayout之前调用

 

4. 设置background后,会重新调用onMeasure和onLayout

 

5. 如果没有直接调用measure并且指定参数,onMeasure的参数是怎么得到的呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值