
上QQ阅读APP看书,第一时间看更新
3.1.1 onMeasure()
在自定义一个View时,要先知道它的大小,所以就需要使用onMeasure()方法对View的大小进行测量:

参数widthMeasureSpec和heightMeasureSpec分别存储了该View的父View的宽和高的信息。什么是宽和高的信息?以widthMeasureSpec为例,它包含了宽的信息,宽的信息就是宽度和测量模式,而heightMeasureSpec包含的则是高度和测量模式。需要注意的是这里的宽度和高度都是父View的宽度和高度。怎么获取这些信息呢?Android提供了一个类MeasureSpec,能直接使用它来获取宽度/高度和测量模式:

再说回这个测量模式的作用,测量模式有3种:
●UNSPECIFIED:View的大小没有限制,可以是任意大小;
●EXACTLY:当前的尺寸大小就是View的大小;
●AT_MOST:View能取的尺寸大小不能超过当前值大小。
所以当开发者在布局中如果指定match_parent则相当于EXACTLY模式,指定wrap_content则相当于AT_MOST模式,而指定具体值也是相当于EXACTLY模式。
回到MyPingredView类中,假设现在想让MyPingredView以长方形的形式显示,默认宽和高分别是100和200,可以使用下面的代码来实现:


然后在布局文件中设置MyPingredView:

布局显示的效果如图3.1所示。