可以说重载onMeasure(),onLayout(),onDraw()三个函数构建了自定义View的外观形象。再加上onTouchEvent()等重载视图的行为,可以构建任何我们需要的可感知到的自定义View。
本节我们探索自定义View中onMeasure()起到了什么样的作用,题外要插的一句是,Activity框架,View框架中大量的on函数基本上都应用到了Template模式,掌握这一模式对于理解这些框架大有裨益。
我们知道,不管是自定义View还是系统提供的TextView这些,它们都必须放置在LinearLayout等一些ViewGroup中,因此理论上我们可以很好的理解onMeasure(),onLayout(),onDraw()这三个函数:1.View本身大小多少,这由onMeasure()决定;2.View在ViewGroup中的位置如何,这由onLayout()决定;3.绘制View,onDraw()定义了如何绘制这个View。
View在屏幕上显示出来要先经过measure(计算)和layout(布局).
1、什么时候调用onMeasure方法?
当控件的父元素正要放置该控件时调用.父元素会问子控件一个问题,“你想要用多大地方啊?”,然后传入两个参数——widthMeasureSpec和heightMeasureSpec.
这两个参数指明控件可获得的空间以及关于这个空间描述的元数据.
更好的方法是你传递View的高度和宽度到setMeasuredDimension方法里,这样可以直接告诉父控件,需要多大地方放置子控件.
接下来的代码片段给出了如何重写 onMeasure.注意,调用的本地空方法是来计算高度和宽度的.它们会译解widthHeightSpec和heightMeasureSpec值,并计算出合适的高度和宽度值.
java代码:
- @Override
- protected void onMeasure(intwidthMeasureSpec, int heightMeasureSpec) {
- int measuredHeight =measureHeight(heightMeasureSpec);
- int measuredWidth = measureWidth(widthMeasureSpec);
- setMeasuredDimension(measuredHeight,measuredWidth);
- }
- private int measureHeight(int measureSpec) {
- // Return measured widget height.
- }
- private int measureWidth(int measureSpec) {
- // Return measured widget width.
- }
- 边界参数——widthMeasureSpec和heightMeasureSpec,效率的原因以整数的方式传入。在它们使用之前,首先要做的是使用MeasureSpec类的静态方法getMode和getSize来译解,如下面的片段所示:
java代码:
- int specMode = MeasureSpec.getMode(measureSpec);
- int specSize = MeasureSpec.getSize(measureSpec);
依据specMode的值,(MeasureSpec有3种模式分别是UNSPECIFIED,EXACTLY和AT_MOST) - int specMode = MeasureSpec.getMode(measureSpec);
- 如果是AT_MOST,specSize代表的是最大可获得的空间;
如果是EXACTLY,specSize 代表的是精确的尺寸;
如果是UNSPECIFIED,对于控件尺寸来说,没有任何参考意义。
2、那么这些模式和我们平时设置的layout参数fill_parent, wrap_content有什么关系呢?
经过代码测试就知道,当我们设置width或height为fill_parent时,容器在布局时调用子view的measure方法传入的模式是EXACTLY,因为子view会占据剩余容器的空间,所以它大小是确定的。
而当设置为 wrap_content时,容器传进去的是AT_MOST,表示子view的大小最多是多少,这样子view会根据这个上限来设置自己的尺寸。当子view的大小设置为精确值时,容器传入的是EXACTLY,而MeasureSpec的UNSPECIFIED模式目前还没有发现在什么情况下使用。
View的onMeasure方法默认行为是当模式为UNSPECIFIED时,设置尺寸为mMinWidth(通常为0)或者背景drawable的最小尺寸,当模式为EXACTLY或者AT_MOST时,尺寸设置为传入的MeasureSpec的大小。
有个观念需要纠正的是,fill_parent应该是子view会占据剩下容器的空间,而不会覆盖前面已布局好的其他view空间,当然后面布局子view就没有空间给分配了,所以fill_parent属性对布局顺序很重要。以前所想的是把所有容器的空间都占满了,难怪google在2.2版本里把fill_parent的名字改为match_parent.
在两种情况下,你必须绝对的处理这些限制。在一些情况下,它可能会返回超出这些限制的尺寸,在这种情况下,你可以让父元素选择如何对待超出的View,使用裁剪还是滚动等技术。
接下来的框架代码给出了处理View测量的典型实现:
java代码:
- @Override
- protected void onMeasure(intwidthMeasureSpec, int heightMeasureSpec) {
- int measuredHeight =measureHeight(heightMeasureSpec);
- int measuredWidth = measureWidth(widthMeasureSpec);
- setMeasuredDimension(measuredHeight, measuredWidth);
- }
- private int measureHeight(int measureSpec) {
- int specMode = MeasureSpec.getMode(measureSpec);
- int specSize = MeasureSpec.getSize(measureSpec);
- // Default size if no limits are specified.
- int result = 500;
- if (specMode == MeasureSpec.AT_MOST){
- // Calculate the ideal size of your
- // control within this maximum size.
- // If your control fills the available
- // space return the outer bound.
- result = specSize;
- }
- else if (specMode == MeasureSpec.EXACTLY){
- // If your control can fit within these bounds return thatvalue.
- result = specSize;
- }
- return result;
- }
- private int measureWidth(int measureSpec) {
- int specMode = MeasureSpec.getMode(measureSpec);
- int specSize = MeasureSpec.getSize(measureSpec);
- // Default size if no limits are specified.
- int result = 500;
- if (specMode == MeasureSpec.AT_MOST){
- // Calculate the ideal size of your control
- // within this maximum size.
- // If your control fills the available space
- // return the outer bound.
- result = specSize;
- }
- else if (specMode == MeasureSpec.EXACTLY){
- // If your control can fit within these bounds return thatvalue.
- result = specSize;
- }
- return result;
- }
- @Override
首先我们看看TextView.java中的onMeasure()源码:
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int widthMode = MeasureSpec.getMode(widthMeasureSpec);
- int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int widthSize = MeasureSpec.getSize(widthMeasureSpec);
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
- int width;
- int height;
- ...
- if (widthMode == MeasureSpec.EXACTLY) {
- // Parent has told us how big to be. So be it.
- width = widthSize;
- } else {
- if (mLayout != null && mEllipsize == null) {
- des = desired(mLayout);
- }
- ...
- setMeasuredDimension(width, height);
首先我们要理解的是widthMeasureSpec, heightMeasureSpec这两个参数是从哪里来的?onMeasure()函数由包含这个View的具体的ViewGroup调用,因此值也是从这个ViewGroup中传入的。这里我直接给出答案:子类View的这两个参数,由ViewGroup中的layout_width,layout_height和padding以及View自身的layout_margin共同决定。权值weight也是尤其需要考虑的因素,有它的存在情况可能会稍微复杂点。
了解了这两个参数的来源,还要知道这两个值的作用。我们只取heightMeasureSpec作说明。这个值由高32位和低16位组成,高32位保存的值叫specMode,可以通过如代码中所示的MeasureSpec.getMode()获取;低16位为specSize,同样可以由MeasureSpec.getSize()获取。那么specMode和specSize的作用有是什么呢?要想知道这一点,我们需要知道代码中的最后一行,所有的View的onMeasure()的最后一行都会调用setMeasureDimension()函数的作用——这个函数调用中传进去的值是View最终的视图大小。也就是说onMeasure()中之前所作的所有工作都是为了最后这一句话服务的。
我们知道在ViewGroup中,给View分配的空间大小并不是确定的,有可能随着具体的变化而变化,而这个变化的条件就是传到specMode中决定的,specMode一共有三种可能:
MeasureSpec.EXACTLY:父视图希望子视图的大小应该是specSize中指定的。
MeasureSpec.AT_MOST:子视图的大小最多是specSize中指定的值,也就是说不建议子视图的大小超过specSize中给定的值。
MeasureSpec.UNSPECIFIED:我们可以随意指定视图的大小。
由TextView中源码也可以知道这个值的设计意义是为了根据ViewGroup中具体能够提供的空间大小来指定子View的视图大小。
通过以上这些分析,可以知道视图最终的大小由父视图,子视图以及程序员根据需要决定,良好的设计一般会根据子视图的measureSpec设置合适的布局大小。
讲到上述这些内容,可能已经了解了如何去使用onMeasure来设置我们的视图的大小,但还有一个疑惑的地方,EXACTLY,AT_MOST,UNSPECIFIED和layout_是如何对应的呢?什么情况下对应什么值呢?
我们通过如下例子,稍作了解:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin" >
- <LinearLayout
- android:layout_width="200dp"
- android:layout_height="wrap_content"
- android:paddingTop="20dp"
- android:layout_marginTop="30dp"
- android:background="@android:color/darker_gray" >
- <com.sean.myview.MyView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingTop="10dp"
- android:layout_marginTop="15dp"
- android:background="@android:color/holo_red_light"
- />
- </LinearLayout>
- </LinearLayout>
效果图如下:
- package com.sean.myview;
- import android.content.Context;
- import android.util.AttributeSet;
- import android.util.Log;
- import android.view.View;
- public class MyView extends View {
- public MyView(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- }
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- // TODO Auto-generated method stub
- Log.d("MyView","------", new Throwable());
- int speSize = MeasureSpec.getSize(heightMeasureSpec);
- int speMode = MeasureSpec.getMode(heightMeasureSpec);
- Log.d("MyView", "---speSize = " + speSize + "");
- Log.d("MyView", "---speMode = " + speMode + "");
- if(speMode == MeasureSpec.AT_MOST){
- Log.d("MyView", "---AT_MOST---");
- }
- if(speMode == MeasureSpec.EXACTLY){
- Log.d("MyView", "---EXACTLY---");
- }
- if(speMode == MeasureSpec.UNSPECIFIED){
- Log.d("MyView", "---UNSPECIFIED---");
- }
- setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), speSize);
- }
- }
当前情况下打印出的log如下:
widthMeasureSpecD/MyView ( 3506): java.lang.Throwable
D/MyView ( 3506): at com.sean.myview.MyView.onMeasure(MyView.java:18)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
D/MyView ( 3506): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1411)
D/MyView ( 3506): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1059)
D/MyView ( 3506): at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
D/MyView ( 3506): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1411)
D/MyView ( 3506): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1059)
D/MyView ( 3506): at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
D/MyView ( 3506): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
D/MyView ( 3506): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
D/MyView ( 3506): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
D/MyView ( 3506): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2193)
D/MyView ( 3506): at android.view.View.measure(View.java:15775)
D/MyView ( 3506): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2212)
D/MyView ( 3506): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1291)
D/MyView ( 3506): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1486)
D/MyView ( 3506): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
D/MyView ( 3506): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
D/MyView ( 3506): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
D/MyView ( 3506): at android.view.Choreographer.doCallbacks(Choreographer.java:579)
D/MyView ( 3506): at android.view.Choreographer.doFrame(Choreographer.java:548)
D/MyView ( 3506): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
D/MyView ( 3506): at android.os.Handler.handleCallback(Handler.java:800)
D/MyView ( 3506): at android.os.Handler.dispatchMessage(Handler.java:100)
D/MyView ( 3506): at android.os.Looper.loop(Looper.java:194)
D/MyView ( 3506): at android.app.ActivityThread.main(ActivityThread.java:5391)
D/MyView ( 3506): at java.lang.reflect.Method.invokeNative(Native Method)
D/MyView ( 3506): at java.lang.reflect.Method.invoke(Method.java:525)
D/MyView ( 3506): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
D/MyView ( 3506): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
D/MyView ( 3506): at dalvik.system.NativeStart.main(Native Method)
D/MyView ( 3506): ---speSize = 940
D/MyView ( 3506): ---speMode = -2147483648
D/MyView ( 3506): ---AT_MOST---
查看onMeasure()的调用堆栈,然后查看源码,可以知道heightMeasureSpec和widthMeasureSpec的值在ViewRootImpl.java中初始化,而初始化又参考了view和LinearLayout中的属性参数的设置最终得到了heightMeasureSpec和widthMeasureSpec的值。
而specMode怎么对应呢?我先给出设置对应值的地方,以下代码皆出自ViewRootImpl.java
- childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
- childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);//这里是赋值的代码
- private static int getRootMeasureSpec(int windowSize, int rootDimension) {
- int measureSpec;
- switch (rootDimension) {
- case ViewGroup.LayoutParams.MATCH_PARENT:
- // Window can't resize. Force root view to be windowSize.
- measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
- break;
- case ViewGroup.LayoutParams.WRAP_CONTENT:
- // Window can resize. Set max size for root view.
- measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
- break;
- default:
- // Window wants to be an exact size. Force root view to be that size.
- measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
- break;
- }
- return measureSpec;
- }
- private void performTraversals() {
- // cache mView since it is used so much below...
- ...
- WindowManager.LayoutParams lp = mWindowAttributes;
- public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
- synchronized (this) {
- if (mView == null) {
- mView = view;
- mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
- mFallbackEventHandler.setView(view);
- mWindowAttributes.copyFrom(attrs);
这个View就是ViewGroup中的各个子类视图,这里我们用实验说明,更改MyView中的android:layout_height的值为"match_parent"。log中输出变为了
D/MyView ( 4249): ---speSize = 940
D/MyView ( 4249): ---speMode = 1073741824
D/MyView ( 4249): ---EXACTLY---
而更改LinearLayout中的这个值对这里的specMode是没有影响的。
下面我们再来通过实验来验证specSize的值由那些属性决定:
- <LinearLayout
- android:layout_width="200dp"
- android:layout_height="300dp"
- android:paddingTop="20dp"
- android:layout_marginTop="30dp"
- android:background="@android:color/darker_gray" >
- <com.sean.myview.MyView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingTop="10dp"
- android:layout_marginTop="15dp"
- android:background="@android:color/holo_red_light"
- />
- </LinearLayout>
D/MyView ( 4959): ---speSize = 530
D/MyView ( 4959): ---speMode = 1073741824
D/MyView ( 4959): ---EXACTLY---
先说明一点,xml中用的单位是dp,log中得到的单位是px,我所使用的机子屏幕密度为2.0,只需要进行简单的换算即可px = 2.0 * dp
我们可以通过控制变量法,逐一改变代码中的LinearLayout和MyView中的相关属性值,看看是哪些影响了specSize,这里我直接给出答案:
530 = 300 * 2.0 - 20 * 2.0 - 15 * 2.0
影响specSize height的因素为:父视图的layout_height和paddingTop以及自身的layout_marginTop。但是我们不要忘记有weight时的影响。
上面这个两个视图是Android API中没有给出来的但在来电接听和闹钟被使用到的一个widget视图——GlowPadView.java
我们通过源码来看看这个View的大小是怎么通过onMeasure来控制的。
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- final int minimumWidth = getSuggestedMinimumWidth();
- final int minimumHeight = getSuggestedMinimumHeight();
- int computedWidth = resolveMeasured(widthMeasureSpec, minimumWidth);
- int computedHeight = resolveMeasured(heightMeasureSpec, minimumHeight);
- ...
- setMeasuredDimension(computedWidth, computedHeight);
- }
- @Override
- protected int getSuggestedMinimumWidth() {
- // View should be large enough to contain the background + handle and
- // target drawable on either edge.
- return (int) (Math.max(mOuterRing.getWidth(), 2 * mOuterRadius) + mMaxTargetWidth);
- }
- private int resolveMeasured(int measureSpec, int desired)
- {
- int result = 0;
- int specSize = MeasureSpec.getSize(measureSpec);
- switch (MeasureSpec.getMode(measureSpec)) {
- case MeasureSpec.UNSPECIFIED:
- result = desired;
- break;
- case MeasureSpec.AT_MOST:
- result = Math.min(specSize, desired);
- break;
- case MeasureSpec.EXACTLY:
- default:
- result = specSize;
- }
- return result;
- }
二是match_parent,对应只有一个父视图的值,这也是符合要求的。