上一篇已经写成功做出一个自定义View ,对基本的方法已经学习了,但是那个View只是一个固定大小的,无法像adnroid其他控件一样,在布局文件中修改大小。那么现在我们得学习一下自定义View设置大小的onMeasure方法!
本来昨天想写的,但是发觉有点没学习状态,后天新功能又要开始做了,再不写怕之后拖拉症又犯,所以今天赶紧整理了下思路,先来学习下onMeasure类的使用。其实这网上百度也有一大堆了,很多也是借鉴的别人的解说,我就归纳一下写一遍加深下自己的印象,印证下自己的理解!
onMeasure
想如系统控件一样控制自己View 的大小,首先直接在类中重写onMeasure,进入源码解释可以得到说明,
* Measure the view and its content to determine the measured width and the * measured height. This method is invoked by {@link #measure(int, int)} and * should be overridden by subclasses to provide accurate and efficient * measurement of their contents.
这是一个测量用的类,也就是绘制宽高设置内容大小的意思吧,
onMeasure:有两个参数,widthMeasureSpec,heightMeasureSpec,表示控件可获得的空间和关于这个空间的元数据。通常由父视图计算后传给子视图,从而有一定的控制子视图的大小。
而用到测量,再翻看学习别人的博客时了解到另一个类:
/** * Measure specification mode: The parent has not imposed any constraint * on the child. It can be whatever size it wants. */ public static final int UNSPECIFIED = 0 << MODE_SHIFT; /** * Measure specification mode: The parent has determined an exact size * for the child. The child is going to be given those bounds regardless * of how big it wants to be. */ public static final int EXACTLY = 1 << MODE_SHIFT; /** * Measure specification mode: The child can be as large as it wants up * to the specified size. */ public static final int AT_MOST = 2 << MODE_SHIFT;