ViewRootImpl类分析View绘制的流程

本文详细剖析了Android中DecorView的绘制流程,包括其如何被添加到窗口、测量、布局及绘制的具体步骤,并深入探讨了View和ViewGroup在这一过程中的作用。

【转载请注明出处:从ViewRootImpl类分析View绘制的流程 CSDN 废墟的树】

从上两篇博客 《从setContentView方法分析Android加载布局流程》 和 《从LayoutInflater分析XML布局解析成View的树形结构的过程》 中我们了解到Activity视图UI是怎么添加到Activity的根布局DecorView上面的。

我们知道Activity中的PhoneView对象帮我们创建了一个PhoneView内部类DecorView(父类为FrameLayout)窗口顶层视图,

然后通过LayoutInflater将xml内容布局解析成View树形结构添加到DecorView顶层视图中id为content的FrameLayout父容器上面。到此,我们已经知道Activity的content内容布局最终

会添加到DecorView窗口顶层视图上面,相信很多人也会有这样的疑惑:窗口顶层视图DecorView是怎么绘制到我们的手机屏幕上的呢?

这篇博客来尝试着分析DecorView的绘制流程。


顶层视图DecorView添加到窗口的过程

DecorView是怎么添加到窗口的呢?这时候我们不得不从Activity是怎么启动的说起,当Activity初始化 Window和将布局添加到

PhoneWindow的内部类DecorView类之后,ActivityThread类会调用handleResumeActivity方法将顶层视图DecorView添加到PhoneWindow窗口,来看看handlerResumeActivity方法的实现:

0-1

Step1

  1. final void handleResumeActivity(IBinder token,  
  2.             boolean clearHide, boolean isForward, boolean reallyResume) {  
  3.   
  4.             ………………  
  5.   
  6.             if (r.window == null && !a.mFinished && willBeVisible) {  
  7.                 //获得当前Activity的PhoneWindow对象  
  8.                 r.window = r.activity.getWindow();  
  9.                 //获得当前phoneWindow内部类DecorView对象  
  10.                 View decor = r.window.getDecorView();  
  11.                 //设置窗口顶层视图DecorView可见度  
  12.                 decor.setVisibility(View.INVISIBLE);  
  13.                 //得当当前Activity的WindowManagerImpl对象  
  14.                 ViewManager wm = a.getWindowManager();  
  15.                 WindowManager.LayoutParams l = r.window.getAttributes();  
  16.                 a.mDecor = decor;  
  17.                 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;  
  18.                 l.softInputMode |= forwardBit;  
  19.                 if (a.mVisibleFromClient) {  
  20.                     //标记根布局DecorView已经添加到窗口  
  21.                     a.mWindowAdded = true;  
  22.                     //将根布局DecorView添加到当前Activity的窗口上面  
  23.                     wm.addView(decor, l);  
  24.   
  25.             …………………  
final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {

            ..................

            if (r.window == null && !a.mFinished && willBeVisible) {
                //获得当前Activity的PhoneWindow对象
                r.window = r.activity.getWindow();
                //获得当前phoneWindow内部类DecorView对象
                View decor = r.window.getDecorView();
                //设置窗口顶层视图DecorView可见度
                decor.setVisibility(View.INVISIBLE);
                //得当当前Activity的WindowManagerImpl对象
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (a.mVisibleFromClient) {
                    //标记根布局DecorView已经添加到窗口
                    a.mWindowAdded = true;
                    //将根布局DecorView添加到当前Activity的窗口上面
                    wm.addView(decor, l);

            .....................

分析:详细步骤以上代码都有详细注释,这里就不一一解释。handlerResumeActivity()方法主要就是通过第 23 行代码将

Activity的顶层视图DecorView添加到窗口视图上。我们来看看WindowManagerImpl类的addView()方法。

  1. @Override  
  2.     public void addView(View view, ViewGroup.LayoutParams params) {  
  3.         mGlobal.addView(view, params, mDisplay, mParentWindow);  
  4.     }  
@Override
    public void addView(View view, ViewGroup.LayoutParams params) {
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

源码很简单,直接调用了 mGlobal对象的addView()方法。继续跟踪,mGlobal对象是WindowManagerGlobal类。进入WindowManagerGlobal类看addView()方法。

0-2

Step2

  1. public void addView(View view, ViewGroup.LayoutParams params,  
  2.            Display display, Window parentWindow) {  
  3.   
  4.        …………  
  5.   
  6.        ViewRootImpl root;  
  7.        View panelParentView = null;  
  8.   
  9.        …………  
  10.   
  11.        //获得ViewRootImpl对象root  
  12.         root = new ViewRootImpl(view.getContext(), display);  
  13.   
  14.        ………..  
  15.   
  16.        // do this last because it fires off messages to start doing things  
  17.        try {  
  18.            //将传进来的参数DecorView设置到root中  
  19.            root.setView(view, wparams, panelParentView);  
  20.        } catch (RuntimeException e) {  
  21.          ………..  
  22.        }  
  23.    }  
 public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {

        ............

        ViewRootImpl root;
        View panelParentView = null;

        ............

        //获得ViewRootImpl对象root
         root = new ViewRootImpl(view.getContext(), display);

        ...........

        // do this last because it fires off messages to start doing things
        try {
            //将传进来的参数DecorView设置到root中
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
          ...........
        }
    }

该方法中创建了一个ViewRootImpl对象root,然后调用ViewRootImpl类中的setView成员方法()。继续跟踪代码进入ViewRootImpl类分析:

0-3

Step3

  1. public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {  
  2.         synchronized (this) {  
  3.             if (mView == null) {  
  4.             //将顶层视图DecorView赋值给全局的mView  
  5.                 mView = view;  
  6.             ………….  
  7.             //标记已添加DecorView  
  8.              mAdded = true;  
  9.             ………….  
  10.             //请求布局  
  11.             requestLayout();  
  12.   
  13.             ………….       
  14.         }  
  15.  }  
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
            //将顶层视图DecorView赋值给全局的mView
                mView = view;
            .............
            //标记已添加DecorView
             mAdded = true;
            .............
            //请求布局
            requestLayout();

            .............     
        }
 }

该方法实现有点长,我省略了其他代码,直接看以上几行代码:

  1. 将外部参数DecorView赋值给mView成员变量
  2. 标记DecorView已添加到ViewRootImpl
  3. 调用requestLayout方法请求布局

0-4

跟踪代码进入到 requestLayout()方法: 
Step4

  1. @Override  
  2.     public void requestLayout() {  
  3.         if (!mHandlingLayoutInLayoutRequest) {  
  4.             checkThread();  
  5.             mLayoutRequested = true;  
  6.             scheduleTraversals();  
  7.         }  
  8.     }  
  9.     …………….  
  10.   
  11. void scheduleTraversals() {  
  12.         if (!mTraversalScheduled) {  
  13.             mTraversalScheduled = true;  
  14.             mTraversalBarrier = mHandler.getLooper().postSyncBarrier();  
  15.             mChoreographer.postCallback(  
  16.                     Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);  
  17.             if (!mUnbufferedInputDispatch) {  
  18.                 scheduleConsumeBatchedInput();  
  19.             }  
  20.             notifyRendererOfFramePending();  
  21.         }  
  22.     }  
  23.   
  24. …………..  
  25.   
  26. final class TraversalRunnable implements Runnable {  
  27.         @Override  
  28.         public void run() {  
  29.             doTraversal();  
  30.         }  
  31.     }  
  32. final TraversalRunnable mTraversalRunnable = new TraversalRunnable();  
  33.   
  34. ……………  
  35.   
  36.  void doTraversal() {  
  37.         if (mTraversalScheduled) {  
  38.             mTraversalScheduled = false;  
  39.             mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);  
  40.   
  41.             try {  
  42.                 performTraversals();  
  43.             } finally {  
  44.                 Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
  45.             }  
  46.         }  
  47.     }  
  48.   
  49. …………  
@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
    ................

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
        }
    }

..............

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

...............

 void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().removeSyncBarrier(mTraversalBarrier);

            try {
                performTraversals();
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
        }
    }

............

跟踪代码,最后DecorView的绘制会进入到ViewRootImpl类中的performTraversals()成员方法,这个过程可以参考上面的代码流程图。现在我们主要来分析下 ViewRootImpl类中的performTraversals()方法。


0-5

Step5


  1. private void performTraversals() {  
  2.         // cache mView since it is used so much below…  
  3.         //我们在Step3知道,mView就是DecorView根布局  
  4.         final View host = mView;  
  5.         //在Step3 成员变量mAdded赋值为true,因此条件不成立  
  6.         if (host == null || !mAdded)  
  7.             return;  
  8.         //是否正在遍历  
  9.         mIsInTraversal = true;  
  10.         //是否马上绘制View  
  11.         mWillDrawSoon = true;  
  12.   
  13.         ………….  
  14.         //顶层视图DecorView所需要窗口的宽度和高度  
  15.         int desiredWindowWidth;  
  16.         int desiredWindowHeight;  
  17.   
  18.         …………………  
  19.         //在构造方法中mFirst已经设置为true,表示是否是第一次绘制DecorView  
  20.         if (mFirst) {  
  21.             mFullRedrawNeeded = true;  
  22.             mLayoutRequested = true;  
  23.             //如果窗口的类型是有状态栏的,那么顶层视图DecorView所需要窗口的宽度和高度就是除了状态栏  
  24.             if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL  
  25.                     || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {  
  26.                 // NOTE – system code, won’t try to do compat mode.  
  27.                 Point size = new Point();  
  28.                 mDisplay.getRealSize(size);  
  29.                 desiredWindowWidth = size.x;  
  30.                 desiredWindowHeight = size.y;  
  31.             } else {//否则顶层视图DecorView所需要窗口的宽度和高度就是整个屏幕的宽高  
  32.                 DisplayMetrics packageMetrics =  
  33.                     mView.getContext().getResources().getDisplayMetrics();  
  34.                 desiredWindowWidth = packageMetrics.widthPixels;  
  35.                 desiredWindowHeight = packageMetrics.heightPixels;  
  36.             }  
  37.     }  
  38. …………  
  39. //获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示DecorView根布局宽和高  
  40.  int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);  
  41.  int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);  
  42.   
  43.   // Ask host how big it wants to be  
  44.   //执行测量操作  
  45.   performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);  
  46.   
  47. ……………………  
  48. //执行布局操作  
  49.  performLayout(lp, desiredWindowWidth, desiredWindowHeight);  
  50.   
  51. …………………..  
  52. //执行绘制操作  
  53. performDraw();  
  54.   
  55. }  
private void performTraversals() {
        // cache mView since it is used so much below...
        //我们在Step3知道,mView就是DecorView根布局
        final View host = mView;
        //在Step3 成员变量mAdded赋值为true,因此条件不成立
        if (host == null || !mAdded)
            return;
        //是否正在遍历
        mIsInTraversal = true;
        //是否马上绘制View
        mWillDrawSoon = true;

        .............
        //顶层视图DecorView所需要窗口的宽度和高度
        int desiredWindowWidth;
        int desiredWindowHeight;

        .....................
        //在构造方法中mFirst已经设置为true,表示是否是第一次绘制DecorView
        if (mFirst) {
            mFullRedrawNeeded = true;
            mLayoutRequested = true;
            //如果窗口的类型是有状态栏的,那么顶层视图DecorView所需要窗口的宽度和高度就是除了状态栏
            if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
                    || lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
                // NOTE -- system code, won't try to do compat mode.
                Point size = new Point();
                mDisplay.getRealSize(size);
                desiredWindowWidth = size.x;
                desiredWindowHeight = size.y;
            } else {//否则顶层视图DecorView所需要窗口的宽度和高度就是整个屏幕的宽高
                DisplayMetrics packageMetrics =
                    mView.getContext().getResources().getDisplayMetrics();
                desiredWindowWidth = packageMetrics.widthPixels;
                desiredWindowHeight = packageMetrics.heightPixels;
            }
    }
............
//获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示DecorView根布局宽和高
 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

  // Ask host how big it wants to be
  //执行测量操作
  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

........................
//执行布局操作
 performLayout(lp, desiredWindowWidth, desiredWindowHeight);

.......................
//执行绘制操作
performDraw();

}

该方法主要流程就体现了View绘制渲染的三个主要步骤,分别是测量,布局,绘制三个阶段。


这里先给出Android系统View的绘制流程:依次执行View类里面的如下三个方法:

  1. measure(int ,int) :测量View的大小
  2. layout(int ,int ,int ,int) :设置子View的位置
  3. draw(Canvas) :绘制View内容到Canvas画布上

测量measure

1-1

从performTraversals方法我们可以看到,在执行performMeasure测量之前要通过getRootMeasureSpec方法获得顶层视图DecorView的测量规格,跟踪代码进入getRootMeasureSpec()方法:

  1. /** 
  2.      * Figures out the measure spec for the root view in a window based on it’s 
  3.      * layout params. 
  4.      * 
  5.      * @param windowSize 
  6.      *            The available width or height of the window 
  7.      * 
  8.      * @param rootDimension 
  9.      *            The layout params for one dimension (width or height) of the 
  10.      *            window. 
  11.      * 
  12.      * @return The measure spec to use to measure the root view. 
  13.      */  
  14.     private static int getRootMeasureSpec(int windowSize, int rootDimension) {  
  15.         int measureSpec;  
  16.         switch (rootDimension) {  
  17.         //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满真个屏幕  
  18.         case ViewGroup.LayoutParams.MATCH_PARENT:  
  19.             // Window can’t resize. Force root view to be windowSize.  
  20.             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);  
  21.             break;  
  22.         //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满真个屏幕  
  23.         case ViewGroup.LayoutParams.WRAP_CONTENT:  
  24.             // Window can resize. Set max size for root view.  
  25.             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);  
  26.             break;  
  27.         //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小。  
  28.         default:  
  29.             // Window wants to be an exact size. Force root view to be that size.  
  30.             measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);  
  31.             break;  
  32.         }  
  33.         return measureSpec;  
  34.     }  
/**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     *
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {
        //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满真个屏幕
        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满真个屏幕
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小。
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

分析:该方法主要作用是在整个窗口的基础上计算出root view(顶层视图DecorView)的测量规格,该方法的两个参数分别表示:

  1. windowSize:当前手机窗口的有效宽和高,一般都是除了通知栏的屏幕宽和高
  2. rootDimension 根布局DecorView请求的宽和高,由前面的博客我们知道是MATCH_PARENT

由 《从setContentView方法分析Android加载布局流程》可知,我们的DecorView根布局宽和高都是MATCH_PARENT,

因此DecorView根布局的测量模式就是MeasureSpec.EXACTLY,测量大小一般都是整个屏幕大小,所以一般我们的Activity

窗口都是全屏的。因此上面代码走第一个分支,通过调用MeasureSpec.makeMeasureSpec方法将

DecorView的测量模式和测量大小封装成DecorView的测量规格。

1-2

由于performMeasure()方法调用了 View中measure()方法俩进行测量,并且DecorView(继承自FrameLayout)的父类是

ViewGroup,祖父类是View。因此我们从View的成员函数measure开始分析整个测量过程。


这个过程分为 3 步,我们来一一分析。

Step1

  1. int mOldWidthMeasureSpec = Integer.MIN_VALUE;  
  2.   
  3.     int mOldHeightMeasureSpec = Integer.MIN_VALUE;  
  4.   
  5.  public final void measure(int widthMeasureSpec, int heightMeasureSpec) {  
  6.   
  7.         ………………  
  8.         //如果上一次的测量规格和这次不一样,则条件满足,重新测量视图View的大小  
  9.         if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||  
  10.                 widthMeasureSpec != mOldWidthMeasureSpec ||  
  11.                 heightMeasureSpec != mOldHeightMeasureSpec) {  
  12.   
  13.             // first clears the measured dimension flag  
  14.             mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;  
  15.   
  16.             resolveRtlPropertiesIfNeeded();  
  17.   
  18.             int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :  
  19.                     mMeasureCache.indexOfKey(key);  
  20.             if (cacheIndex < 0 || sIgnoreMeasureCache) {  
  21.                 // measure ourselves, this should set the measured dimension flag back  
  22.                 onMeasure(widthMeasureSpec, heightMeasureSpec);  
  23.                 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  
  24.             } else {  
  25.                 long value = mMeasureCache.valueAt(cacheIndex);  
  26.                 // Casting a long to int drops the high 32 bits, no mask needed  
  27.                 setMeasuredDimensionRaw((int) (value >> 32), (int) value);  
  28.                 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  
  29.             }  
  30.   
  31.             mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;  
  32.         }  
  33.   
  34.         mOldWidthMeasureSpec = widthMeasureSpec;  
  35.         mOldHeightMeasureSpec = heightMeasureSpec;  
  36.   
  37.     }  
int mOldWidthMeasureSpec = Integer.MIN_VALUE;

    int mOldHeightMeasureSpec = Integer.MIN_VALUE;

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {

        ..................
        //如果上一次的测量规格和这次不一样,则条件满足,重新测量视图View的大小
        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

    }

分析: 
1.代码第10行:判断当前视图View是否需要重新测量,当上一次视图View测量的规格和本次视图View测量规格不一样时,就说明视图View的大小有改变,因此需要重新测量。

2.代码第23行:调用了onMeasure方法进行测量,说明View主要的测量逻辑是在该方法中实现。

3.代码第35-36行:保存本次视图View的测量规格到mOldWidthMeasureSpec和mOldHeightMeasureSpec以便下次测量条件的判断是否需要重新测量。

1-3

跟踪代码,进入View类的 onMeasure方法

  1. /** 
  2.      * <p> 
  3.      * Measure the view and its content to determine the measured width and the 
  4.      * measured height. This method is invoked by {@link #measure(int, int)} and 
  5.      * should be overriden by subclasses to provide accurate and efficient 
  6.      * measurement of their contents. 
  7.      * </p> 
  8.      * 
  9.      * <p> 
  10.      * <strong>CONTRACT:</strong> When overriding this method, you 
  11.      * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 
  12.      * measured width and height of this view. Failure to do so will trigger an 
  13.      * <code>IllegalStateException</code>, thrown by 
  14.      * {@link #measure(int, int)}. Calling the superclass’ 
  15.      * {@link #onMeasure(int, int)} is a valid use. 
  16.      * </p> 
  17.      * 
  18.      * <p> 
  19.      * The base class implementation of measure defaults to the background size, 
  20.      * unless a larger size is allowed by the MeasureSpec. Subclasses should 
  21.      * override {@link #onMeasure(int, int)} to provide better measurements of 
  22.      * their content. 
  23.      * </p> 
  24.      * 
  25.      * <p> 
  26.      * If this method is overridden, it is the subclass’s responsibility to make 
  27.      * sure the measured height and width are at least the view’s minimum height 
  28.      * and width ({@link #getSuggestedMinimumHeight()} and 
  29.      * {@link #getSuggestedMinimumWidth()}). 
  30.      * </p> 
  31.      * 
  32.      * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 
  33.      *                         The requirements are encoded with 
  34.      *                         {@link android.view.View.MeasureSpec}. 
  35.      * @param heightMeasureSpec vertical space requirements as imposed by the parent. 
  36.      *                         The requirements are encoded with 
  37.      *                         {@link android.view.View.MeasureSpec}. 
  38.      * 
  39.      * @see #getMeasuredWidth() 
  40.      * @see #getMeasuredHeight() 
  41.      * @see #setMeasuredDimension(int, int) 
  42.      * @see #getSuggestedMinimumHeight() 
  43.      * @see #getSuggestedMinimumWidth() 
  44.      * @see android.view.View.MeasureSpec#getMode(int) 
  45.      * @see android.view.View.MeasureSpec#getSize(int) 
  46.      */  
  47.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  48.         setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
  49.                 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
  50.     }  
/**
     * <p>
     * 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 overriden by subclasses to provide accurate and efficient
     * measurement of their contents.
     * </p>
     *
     * <p>
     * <strong>CONTRACT:</strong> When overriding this method, you
     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
     * measured width and height of this view. Failure to do so will trigger an
     * <code>IllegalStateException</code>, thrown by
     * {@link #measure(int, int)}. Calling the superclass'
     * {@link #onMeasure(int, int)} is a valid use.
     * </p>
     *
     * <p>
     * The base class implementation of measure defaults to the background size,
     * unless a larger size is allowed by the MeasureSpec. Subclasses should
     * override {@link #onMeasure(int, int)} to provide better measurements of
     * their content.
     * </p>
     *
     * <p>
     * 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 ({@link #getSuggestedMinimumHeight()} and
     * {@link #getSuggestedMinimumWidth()}).
     * </p>
     *
     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     *
     * @see #getMeasuredWidth()
     * @see #getMeasuredHeight()
     * @see #setMeasuredDimension(int, int)
     * @see #getSuggestedMinimumHeight()
     * @see #getSuggestedMinimumWidth()
     * @see android.view.View.MeasureSpec#getMode(int)
     * @see android.view.View.MeasureSpec#getSize(int)
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

分析: 
该方法的实现也很简单,直接调用setMeasuredDimension方法完成视图View的测量。我们知道,android中所有的视图组件都是继承自View实现的。因此该方法提供了一个默认测量视图View大小的实现。

1-4

言外之意,如果你不想你自己的View使用默认实现来测量View的宽高的话,你可以在子类中重写onMeasure方法来自定义测量方法。我们先来看看默认测量宽高的实现。跟踪代码进入getDefaultSize方法:

  1. /** 
  2.      * Utility to return a default size. Uses the supplied size if the 
  3.      * MeasureSpec imposed no constraints. Will get larger if allowed 
  4.      * by the MeasureSpec. 
  5.      * 
  6.      * @param size Default size for this view 
  7.      * @param measureSpec Constraints imposed by the parent 
  8.      * @return The size this view should be. 
  9.      */  
  10.     public static int getDefaultSize(int size, int measureSpec) {  
  11.         int result = size;  
  12.         //获得测量模式  
  13.         int specMode = MeasureSpec.getMode(measureSpec);  
  14.         //获得父亲容器留给子视图View的大小  
  15.         int specSize = MeasureSpec.getSize(measureSpec);  
  16.   
  17.         switch (specMode) {  
  18.         case MeasureSpec.UNSPECIFIED:  
  19.             result = size;  
  20.             break;  
  21.         case MeasureSpec.AT_MOST:  
  22.         case MeasureSpec.EXACTLY:  
  23.             result = specSize;  
  24.             break;  
  25.         }  
  26.         return result;  
  27.     }  
/**
     * Utility to return a default size. Uses the supplied size if the
     * MeasureSpec imposed no constraints. Will get larger if allowed
     * by the MeasureSpec.
     *
     * @param size Default size for this view
     * @param measureSpec Constraints imposed by the parent
     * @return The size this view should be.
     */
    public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        //获得测量模式
        int specMode = MeasureSpec.getMode(measureSpec);
        //获得父亲容器留给子视图View的大小
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

分析:该方法的作用是根据View布局设置的宽高和父View传递的测量规格重新计算View的测量宽高。由此可以知道,我们布局的

子View最终的大小是由布局大小和父容器的测量规格共同决定的。如果自定义View你没有重写onMeasure使用系统默认方法的

话,测量模式MeasureSpec.AT_MOST和MeasureSpec.EXACTLY下的测量大小是一样的。我们来总结一下测量模式的种类:

  1. MeasureSpec.EXACTLY:确定模式,父容器希望子视图View的大小是固定,也就是specSize大小。
  2. MeasureSpec.AT_MOST:最大模式,父容器希望子视图View的大小不超过父容器希望的大小,也就是不超过specSize大小。
  3. MeasureSpec.UNSPECIFIED: 不确定模式,子视图View请求多大就是多大,父容器不限制其大小范围,也就是size大小。

从上面代码可以看出,当测量模式是MeasureSpec.UNSPECIFIED时,View的测量值为size,当测量模式为

MeasureSpec.AT_MOST或者case MeasureSpec.EXACTLY时,View的测量值为specSize。我们知道,specSize是由父容器决

定,那么size是怎么计算出来的呢?getDefaultSize方法的第一个参数是调用getSuggestedMinimumWidth方法获得。进入getSuggestedMinimumWidth方法看看实现:

  1. /** 
  2.      * Returns the suggested minimum width that the view should use. This 
  3.      * returns the maximum of the view’s minimum width) 
  4.      * and the background’s minimum width 
  5.      *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 
  6.      * <p> 
  7.      * When being used in {@link #onMeasure(int, int)}, the caller should still 
  8.      * ensure the returned width is within the requirements of the parent. 
  9.      * 
  10.      * @return The suggested minimum width of the view. 
  11.      */  
  12.     protected int getSuggestedMinimumWidth() {  
  13.         return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());  
  14.     }  
/**
     * Returns the suggested minimum width that the view should use. This
     * returns the maximum of the view's minimum width)
     * and the background's minimum width
     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
     * <p>
     * When being used in {@link #onMeasure(int, int)}, the caller should still
     * ensure the returned width is within the requirements of the parent.
     *
     * @return The suggested minimum width of the view.
     */
    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

原来size大小是获取View属性当中的最小值,也就是 android:minWidth和 android:minHeight的值,前提是View没有设置背景属性。否则就在最小值和背景的最小值中间取最大值。

sizeSpec大小是有父容器决定的,我们由 1-1节知道父容器DecorView的测量模式是MeasureSpec.EXACTLY,测量大小sizeSpec是整个屏幕的大小。

setp2 
而DecorView是继承自FrameLayout的,那么我们来看看FrameLayout类中的onMeasure方法的实现

  1. @Override  
  2.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.         int count = getChildCount();  
  4.         …………..  
  5.         int maxHeight = 0;  
  6.         int maxWidth = 0;  
  7.         int childState = 0;  
  8.   
  9.         for (int i = 0; i < count; i++) {  
  10.             final View child = getChildAt(i);  
  11.             if (mMeasureAllChildren || child.getVisibility() != GONE) {  
  12.                 //测量FrameLayout下每个子视图View的宽和高  
  13.                 measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);  
  14.                 final LayoutParams lp = (LayoutParams) child.getLayoutParams();  
  15.                 maxWidth = Math.max(maxWidth,  
  16.                         child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);  
  17.                 maxHeight = Math.max(maxHeight,  
  18.                         child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);  
  19.                 childState = combineMeasuredStates(childState, child.getMeasuredState());  
  20.                 if (measureMatchParentChildren) {  
  21.                     if (lp.width == LayoutParams.MATCH_PARENT ||  
  22.                             lp.height == LayoutParams.MATCH_PARENT) {  
  23.                         mMatchParentChildren.add(child);  
  24.                     }  
  25.                 }  
  26.             }  
  27.         }  
  28.   
  29.         // Account for padding too  
  30.         maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();  
  31.         maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();  
  32.   
  33.         // Check against our minimum height and width  
  34.         maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());  
  35.         maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());  
  36.   
  37.         // Check against our foreground’s minimum height and width  
  38.         final Drawable drawable = getForeground();  
  39.         if (drawable != null) {  
  40.             maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());  
  41.             maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());  
  42.         }  
  43.         //设置当前FrameLayout测量结果,此方法的调用表示当前View测量的结束。  
  44.         setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),  
  45.                 resolveSizeAndState(maxHeight, heightMeasureSpec,  
  46.                         childState << MEASURED_HEIGHT_STATE_SHIFT));  
  47. }  
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        ..............
        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                //测量FrameLayout下每个子视图View的宽和高
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }
        //设置当前FrameLayout测量结果,此方法的调用表示当前View测量的结束。
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));
}

分析:由以上代码发现,ViewGroup测量结果都是带边距的,代码第9-27行就是遍历测量FrameLayout下子视图View的大小了。

代码第44行,最后调用setMeasuredDimension方法设置当前View的测量结果,此方法的调用表示当前View测量结束。

那么我们来分析下代码第12行measureChildWithMargins方法测量FrameLayout下的子视图View的大小,跟踪源码:

Step3: 
由于FrameLayout父类是ViewGroup,measureChildWithMargins方法在ViewGroup下

  1. /** 
  2.      * Ask one of the children of this view to measure itself, taking into 
  3.      * account both the MeasureSpec requirements for this view and its padding 
  4.      * and margins. The child must have MarginLayoutParams The heavy lifting is 
  5.      * done in getChildMeasureSpec. 
  6.      * 
  7.      * @param child The child to measure 
  8.      * @param parentWidthMeasureSpec The width requirements for this view 
  9.      * @param widthUsed Extra space that has been used up by the parent 
  10.      *        horizontally (possibly by other children of the parent) 
  11.      * @param parentHeightMeasureSpec The height requirements for this view 
  12.      * @param heightUsed Extra space that has been used up by the parent 
  13.      *        vertically (possibly by other children of the parent) 
  14.      */  
  15.     protected void measureChildWithMargins(View child,  
  16.             int parentWidthMeasureSpec, int widthUsed,  
  17.             int parentHeightMeasureSpec, int heightUsed) {  
  18.         final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  
  19.   
  20.         final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,  
  21.                 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin  
  22.                         + widthUsed, lp.width);  
  23.         final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,  
  24.                 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin  
  25.                         + heightUsed, lp.height);  
  26.   
  27.         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
  28.     }  
/**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding
     * and margins. The child must have MarginLayoutParams The heavy lifting is
     * done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param widthUsed Extra space that has been used up by the parent
     *        horizontally (possibly by other children of the parent)
     * @param parentHeightMeasureSpec The height requirements for this view
     * @param heightUsed Extra space that has been used up by the parent
     *        vertically (possibly by other children of the parent)
     */
    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

分析:该方法中调用getChildMeasureSpec方法来获得ViewGroup下的子视图View的测量规格。然后将测量规格最为参数传递给

View的measure方法,最终完成所有子视图View的测量。来看看这里是怎么获得子视图View的测量规格的,进入getChildMeasureSpec方法:

  1. public static int getChildMeasureSpec(int spec, int padding, int childDimension) {  
  2.         int specMode = MeasureSpec.getMode(spec);  
  3.         int specSize = MeasureSpec.getSize(spec);  
  4.   
  5.         int size = Math.max(0, specSize - padding);  
  6.   
  7.         int resultSize = 0;  
  8.         int resultMode = 0;  
  9.   
  10.         switch (specMode) {  
  11.         // Parent has imposed an exact size on us  
  12.         case MeasureSpec.EXACTLY:  
  13.             if (childDimension >= 0) {  
  14.                 resultSize = childDimension;  
  15.                 resultMode = MeasureSpec.EXACTLY;  
  16.             } else if (childDimension == LayoutParams.MATCH_PARENT) {  
  17.                 // Child wants to be our size. So be it.  
  18.                 resultSize = size;  
  19.                 resultMode = MeasureSpec.EXACTLY;  
  20.             } else if (childDimension == LayoutParams.WRAP_CONTENT) {  
  21.                 // Child wants to determine its own size. It can’t be  
  22.                 // bigger than us.  
  23.                 resultSize = size;  
  24.                 resultMode = MeasureSpec.AT_MOST;  
  25.             }  
  26.             break;  
  27.   
  28.        ………..  
  29.   
  30.         }  
  31.         return MeasureSpec.makeMeasureSpec(resultSize, resultMode);  
  32.     }  
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

       ...........

        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

分析:由1-1节我们知道根布局DecorView的测量规格中的测量模式是MeasureSpec.EXACTLY,测量大小是整个窗口大小。因此上面代码分支走MeasureSpec.EXACTLY。子视图View的测量规格由其宽和高参数决定。

  1. 当DecorView根布局的子视图View宽高为一个确定值childDimension时,该View的测量模式为MeasureSpec.EXACTLY,测量大小就是childDimension。
  2. 当子视图View宽高为MATCH_PARENT时,该View的测量模式为MeasureSpec.EXACTLY,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。
  3. 当子视图View宽高为WRAP_CONTENT时,该View的测量模式为MeasureSpec.AT_MOST,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。
至此,整个View树型结构的布局测量流程可以归纳如下:

measure总结

  1. View的measure方法是final类型的,子类不可以重写,子类可以通过重写onMeasure方法来测量自己的大小,当然也可以不重写onMeasure方法使用系统默认测量大小。
  2. View测量结束的标志是调用了View类中的setMeasuredDimension成员方法,言外之意是,如果你需要在自定义的View中重写onMeasure方法,在你测量结束之前你必须调用setMeasuredDimension方法测量才有效。
  3. 在Activity生命周期onCreate和onResume方法中调用View.getWidth()和View.getMeasuredHeight()返回值为0的,是因为当前View的测量还没有开始,这里关系到Activity启动过程,文章开头说了当ActivityThread类中的performResumeActivity方法执行之后才将DecorView添加到PhoneWindow窗口上,开始测量。在Activity生命周期onCreate在中performResumeActivity还为执行,因此调用View.getMeasuredHeight()返回值为0。
  4. 子视图View的大小是由父容器View和子视图View布局共同决定的。

布局Layout

由 0-5节可知,View视图绘制流程中的布局layout是由ViewRootImpl中的performLayout成员方法开始的,看源码:

2-1

  1. private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,  
  2.            int desiredWindowHeight) {  
  3.        ………………  
  4.        //标记当前开始布局  
  5.        mInLayout = true;  
  6.        //mView就是DecorView  
  7.        final View host = mView;  
  8.        ………………  
  9.        //DecorView请求布局  
  10.        host.layout(00, host.getMeasuredWidth(), host.getMeasuredHeight());  
  11.        //标记布局结束  
  12.        mInLayout = false;  
  13.        ………………  
 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        ..................
        //标记当前开始布局
        mInLayout = true;
        //mView就是DecorView
        final View host = mView;
        ..................
        //DecorView请求布局
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        //标记布局结束
        mInLayout = false;
        ..................
}

分析: 
代码第10行发现,DecorView的四个位置左=0,顶=0,右=屏幕宽,底=屏幕宽,说明DecorView布局的位置是从屏幕最左最顶端开始布局,到屏幕最低最右结束。因此DecorView根布局是充满整个屏幕的。

该方法主要调用了View类的layout方法,跟踪代码进入View类的layout方法瞧瞧吧

2-2

  1. /** 
  2.      * Assign a size and position to a view and all of its 
  3.      * descendants 
  4.      * 
  5.      * <p>This is the second phase of the layout mechanism. 
  6.      * (The first is measuring). In this phase, each parent calls 
  7.      * layout on all of its children to position them. 
  8.      * This is typically done using the child measurements 
  9.      * that were stored in the measure pass().</p> 
  10.      * 
  11.      * <p>Derived classes should not override this method. 
  12.      * Derived classes with children should override 
  13.      * onLayout. In that method, they should 
  14.      * call layout on each of their children.</p> 
  15.      * 
  16.      * @param l Left position, relative to parent 
  17.      * @param t Top position, relative to parent 
  18.      * @param r Right position, relative to parent 
  19.      * @param b Bottom position, relative to parent 
  20.      */  
  21.     @SuppressWarnings({“unchecked”})  
  22.     public void layout(int l, int t, int r, int b) {  
  23.         //判断是否需要重新测量  
  24.         if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {  
  25.             <strong>onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);</strong>  
  26.             mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  
  27.         }  
  28.         //保存上一次View的四个位置  
  29.         int oldL = mLeft;  
  30.         int oldT = mTop;  
  31.         int oldB = mBottom;  
  32.         int oldR = mRight;  
  33.         //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变  
  34.         boolean changed = isLayoutModeOptical(mParent) ?  
  35.                 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);  
  36.         //如果布局有改变,条件成立,则视图View重新布局  
  37.             if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {  
  38.             //调用onLayout,将具体布局逻辑留给子类实现  
  39.             onLayout(changed, l, t, r, b);  
  40.             mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;  
  41.   
  42.             ListenerInfo li = mListenerInfo;  
  43.             if (li != null && li.mOnLayoutChangeListeners != null) {  
  44.                 ArrayList<OnLayoutChangeListener> listenersCopy =  
  45.                         (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();  
  46.                 int numListeners = listenersCopy.size();  
  47.                 for (int i = 0; i < numListeners; ++i) {  
  48.                     listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);  
  49.                 }  
  50.             }  
  51.         }  
  52.   
  53.         mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;  
  54.         mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;  
  55.     }  
/**
     * Assign a size and position to a view and all of its
     * descendants
     *
     * <p>This is the second phase of the layout mechanism.
     * (The first is measuring). In this phase, each parent calls
     * layout on all of its children to position them.
     * This is typically done using the child measurements
     * that were stored in the measure pass().</p>
     *
     * <p>Derived classes should not override this method.
     * Derived classes with children should override
     * onLayout. In that method, they should
     * call layout on each of their children.</p>
     *
     * @param l Left position, relative to parent
     * @param t Top position, relative to parent
     * @param r Right position, relative to parent
     * @param b Bottom position, relative to parent
     */
    @SuppressWarnings({"unchecked"})
    public void layout(int l, int t, int r, int b) {
        //判断是否需要重新测量
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            <strong>onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);</strong>
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }
        //保存上一次View的四个位置
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;
        //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
        //如果布局有改变,条件成立,则视图View重新布局
            if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            //调用onLayout,将具体布局逻辑留给子类实现
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }

分析: 
1.代码第23-32行保存本次布局的四个位置,用于布局变化的监听事件,如果用户设置了布局变化的监听事件,则代码第43-50就会执行设置监听事件。

2.代码第34-35行设置当前View的布局位置,也就是当调用了setFrame(l, t, r, b)方法之后,当前View布局基本完成,既然这样为什么还要第39行 onLayout方法呢?稍后解答,这里来分析一下setFrame是怎么设置当前View的布局位置的。

进入setFrame方法

2-3

  1. /** 
  2.      * Assign a size and position to this view. 
  3.      * 
  4.      * This is called from layout. 
  5.      * 
  6.      * @param left Left position, relative to parent 
  7.      * @param top Top position, relative to parent 
  8.      * @param right Right position, relative to parent 
  9.      * @param bottom Bottom position, relative to parent 
  10.      * @return true if the new size and position are different than the 
  11.      *         previous ones 
  12.      * {@hide} 
  13.      */  
  14.     protected boolean setFrame(int left, int top, int right, int bottom) {  
  15.         boolean changed = false;  
  16.         //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局  
  17.         if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {  
  18.             changed = true;  
  19.   
  20.             // Remember our drawn bit  
  21.             int drawn = mPrivateFlags & PFLAG_DRAWN;  
  22.             //得到本次和上次的宽和高  
  23.             int oldWidth = mRight - mLeft;  
  24.             int oldHeight = mBottom - mTop;  
  25.             int newWidth = right - left;  
  26.             int newHeight = bottom - top;  
  27.             //判断本次View的宽高和上次View的宽高是否相等  
  28.             boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);  
  29.   
  30.             // Invalidate our old position  
  31.             //清楚上次布局的位置  
  32.             invalidate(sizeChanged);  
  33.             //保存当前View的最新位置  
  34.             mLeft = left;  
  35.             mTop = top;  
  36.             mRight = right;  
  37.             mBottom = bottom;  
  38.             mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);  
  39.   
  40.             mPrivateFlags |= PFLAG_HAS_BOUNDS;  
  41.   
  42.             //如果当前View的尺寸有所变化  
  43.             if (sizeChanged) {  
  44.                 sizeChange(newWidth, newHeight, oldWidth, oldHeight);  
  45.             }  
  46.   
  47.             ……………  
  48.         return changed;  
  49.     }  
/**
     * Assign a size and position to this view.
     *
     * This is called from layout.
     *
     * @param left Left position, relative to parent
     * @param top Top position, relative to parent
     * @param right Right position, relative to parent
     * @param bottom Bottom position, relative to parent
     * @return true if the new size and position are different than the
     *         previous ones
     * {@hide}
     */
    protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
        //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;

            // Remember our drawn bit
            int drawn = mPrivateFlags & PFLAG_DRAWN;
            //得到本次和上次的宽和高
            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            //判断本次View的宽高和上次View的宽高是否相等
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

            // Invalidate our old position
            //清楚上次布局的位置
            invalidate(sizeChanged);
            //保存当前View的最新位置
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

            mPrivateFlags |= PFLAG_HAS_BOUNDS;

            //如果当前View的尺寸有所变化
            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }

            ...............
        return changed;
    }

分析: 
1.代码第17行,如果当前View视图的最新位置和上一次不一样时,则View会重新布局。

2.代码第32-38行,保存当前View的最新位置,到此当前View的布局基本结束。从这里我们可以看到,四个全局变量 mLeft,mTop,mRight,mBottom在此刻赋值,联想我们平时使用的View.getWidth()方法获得View的宽高,你可以发现,其实View.getWidth()方法的实现如下:

  1. public final int getWidth() {  
  2.         return mRight - mLeft;  
  3.     }  
  4.  public final int getHeight() {  
  5.         return mBottom - mTop;  
  6.     }  
public final int getWidth() {
        return mRight - mLeft;
    }
 public final int getHeight() {
        return mBottom - mTop;
    }


也就是说,以上两个方法是获得View布局时候的宽高,因此,我们只有在View 布局完之后调用getWidth才能真正获取到大于0的值。

2-4

细心的你会发现,既然2-3小节调用了setFrame方法,也就是当前View的布局结束了,那么View中的onLayout方法又是干嘛的呢?进入onLayout方法:

  1. /** 
  2.      * Called from layout when this view should 
  3.      * assign a size and position to each of its children. 
  4.      * 
  5.      * Derived classes with children should override 
  6.      * this method and call layout on each of 
  7.      * their children. 
  8.      * @param changed This is a new size or position for this view 
  9.      * @param left Left position, relative to parent 
  10.      * @param top Top position, relative to parent 
  11.      * @param right Right position, relative to parent 
  12.      * @param bottom Bottom position, relative to parent 
  13.      */  
  14.     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  15.     }  
/**
     * Called from layout when this view should
     * assign a size and position to each of its children.
     *
     * Derived classes with children should override
     * this method and call layout on each of
     * their children.
     * @param changed This is a new size or position for this view
     * @param left Left position, relative to parent
     * @param top Top position, relative to parent
     * @param right Right position, relative to parent
     * @param bottom Bottom position, relative to parent
     */
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

分析:原来这是一个空方法,既然是空方法,那么该方法的实现应该在子类中。前面分析过,DecorView是继承自FrameLayout的,那么进入FarmeLayout类中看看 onLayout方法的实现吧:

  1. * {@inheritDoc}  
  2.     */  
  3.    @Override  
  4.    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  5.        layoutChildren(left, top, right, bottom, false /* no force left gravity */);  
  6.    }  
  7.   
  8.    void layoutChildren(int left, int top, int right, int bottom,  
  9.                                  boolean forceLeftGravity) {  
  10.        final int count = getChildCount();  
  11.   
  12.        final int parentLeft = getPaddingLeftWithForeground();  
  13.        final int parentRight = right - left - getPaddingRightWithForeground();  
  14.   
  15.        final int parentTop = getPaddingTopWithForeground();  
  16.        final int parentBottom = bottom - top - getPaddingBottomWithForeground();  
  17.   
  18.        mForegroundBoundsChanged = true;  
  19.        //遍历当前FrameLayout下的子View  
  20.        for (int i = 0; i < count; i++) {  
  21.            final View child = getChildAt(i);  
  22.            //当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的。  
  23.            if (child.getVisibility() != GONE) {  
  24.                final LayoutParams lp = (LayoutParams) child.getLayoutParams();  
  25.                //获得子视图View的宽高  
  26.                final int width = child.getMeasuredWidth();  
  27.                final int height = child.getMeasuredHeight();  
  28.   
  29.                int childLeft;  
  30.                int childTop;  
  31.   
  32.                int gravity = lp.gravity;  
  33.                if (gravity == -1) {  
  34.                    gravity = DEFAULT_CHILD_GRAVITY;  
  35.                }  
  36.   
  37.                final int layoutDirection = getLayoutDirection();  
  38.                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);  
  39.                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;  
  40.                //一下代码获得子视图View的四个位置,用于子视图View布局。  
  41.                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {  
  42.                    case Gravity.CENTER_HORIZONTAL:  
  43.                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +  
  44.                        lp.leftMargin - lp.rightMargin;  
  45.                        break;  
  46.                    case Gravity.RIGHT:  
  47.                        if (!forceLeftGravity) {  
  48.                            childLeft = parentRight - width - lp.rightMargin;  
  49.                            break;  
  50.                        }  
  51.                    case Gravity.LEFT:  
  52.                    default:  
  53.                        childLeft = parentLeft + lp.leftMargin;  
  54.                }  
  55.   
  56.                switch (verticalGravity) {  
  57.                    case Gravity.TOP:  
  58.                        childTop = parentTop + lp.topMargin;  
  59.                        break;  
  60.                    case Gravity.CENTER_VERTICAL:  
  61.                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +  
  62.                        lp.topMargin - lp.bottomMargin;  
  63.                        break;  
  64.                    case Gravity.BOTTOM:  
  65.                        childTop = parentBottom - height - lp.bottomMargin;  
  66.                        break;  
  67.                    default:  
  68.                        childTop = parentTop + lp.topMargin;  
  69.                }  
  70.                //子视图布局  
  71.                child.layout(childLeft, childTop, childLeft + width, childTop + height);  
  72.            }  
  73.        }  
  74.    }  
 * {@inheritDoc}
     */
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

    void layoutChildren(int left, int top, int right, int bottom,
                                  boolean forceLeftGravity) {
        final int count = getChildCount();

        final int parentLeft = getPaddingLeftWithForeground();
        final int parentRight = right - left - getPaddingRightWithForeground();

        final int parentTop = getPaddingTopWithForeground();
        final int parentBottom = bottom - top - getPaddingBottomWithForeground();

        mForegroundBoundsChanged = true;
        //遍历当前FrameLayout下的子View
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            //当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的。
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                //获得子视图View的宽高
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = DEFAULT_CHILD_GRAVITY;
                }

                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
                //一下代码获得子视图View的四个位置,用于子视图View布局。
                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                        lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        if (!forceLeftGravity) {
                            childLeft = parentRight - width - lp.rightMargin;
                            break;
                        }
                    case Gravity.LEFT:
                    default:
                        childLeft = parentLeft + lp.leftMargin;
                }

                switch (verticalGravity) {
                    case Gravity.TOP:
                        childTop = parentTop + lp.topMargin;
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                        lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = parentBottom - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = parentTop + lp.topMargin;
                }
                //子视图布局
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
    }

分析:在FrameLayout中的onLayout方法中仅仅是调用了layoutChildren方法,从该方法名称我们不难看出,原来该方法的作用是

给子视图View进行布局的。也就是说FrameLayout布局其实在View类中的layout方法中已经实现,布局的逻辑实现是在父视图中

实现的,不像View视图的measure测量,通过子类实现onMeasure方法来实现测量逻辑。

1.代码第20-71行,遍历获得FrameLayout的子视图View的四个位置,然后调用child.layout对子视图View进行布局操作。

2.代码第23行,对每个子视图View的可见度进行了判断,如果当前子视图View可见度类型为GONE,则当前子视图View不进行布局,这也就是为什么可见度GONE类型时是不占据屏幕空间的,而其他两种VISIBLE和INVISIBLE是占据屏幕空间的。

2-5

由于FrameLayout类是继承自ViewGroup类的,那么我们进入ViewGroup类去窥探一下onLayout方法具体做了什么?

  1. /** 
  2.      * {@inheritDoc} 
  3.      */  
  4.     @Override  
  5.     protected abstract void onLayout(boolean changed,  
  6.             int l, int t, int r, int b);  
/**
     * {@inheritDoc}
     */
    @Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

你会惊讶的发现,在ViewGroup类中的onLayout方法居然是一个抽象方法,现在你明白了吧?我们的FrameLayout继承自ViewGroup,自然FrameLayout就必须实现ViewGroup中的抽象方法onLayout,而FrameLyayout中的onLayout方法的作用是用来设置它的子视图View的布局位置。

到此,我们的布局流程可以用如下图表示:


layout布局总结

1.视图View的布局逻辑是由父View,也就是ViewGroup容器布局来实现的。因此,我们如果自定义View一般都无需重写onMeasure方法,但是如果自定义一个ViewGroup容器的话,就必须实现onMeasure方法,因为该方法在ViewGroup是抽象的,所有ViewGroup的所有子类必须实现onMeasure方法。

2.当我们的视图View在布局中使用 android:visibility=”gone” 属性时,是不占据屏幕空间的,因为在布局时ViewGroup会遍历每个子视图View,判断当前子视图View是否设置了 Visibility==GONE,如果设置了,当前子视图View就会添加到父容器上,因此也就不占据屏幕空间。具体可以参考2-4节。

3.必须在View布局完之后调用getHeight()和getWidth()方法获取到的View的宽高才大于0。具体可以参考2-3节。

View的绘制Draw

由 0-5节可知,View视图绘制流程中的最后一步绘制draw是由ViewRootImpl中的performDraw成员方法开始的,跟踪代码,最后会在ViewRootImpl类中的drawSoftware方法绘制View:

3-1

  1. private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,  
  2.             boolean scalingRequired, Rect dirty) {  
  3.   
  4.         // Draw with software renderer.  
  5.         final Canvas canvas;  
  6.         try {  
  7.             //从surface对象中获得canvas变量  
  8.             canvas = mSurface.lockCanvas(dirty);  
  9.   
  10.             // If this bitmap’s format includes an alpha channel, we  
  11.             // need to clear it before drawing so that the child will  
  12.             // properly re-composite its drawing on a transparent  
  13.             // background. This automatically respects the clip/dirty region  
  14.             // or  
  15.             // If we are applying an offset, we need to clear the area  
  16.             // where the offset doesn’t appear to avoid having garbage  
  17.             // left in the blank areas.  
  18.             if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {  
  19.                 canvas.drawColor(0, PorterDuff.Mode.CLEAR);  
  20.             }  
  21.   
  22.            ………………….  
  23.   
  24.             try {  
  25.                 //调整画布的位置  
  26.                 canvas.translate(-xoff, -yoff);  
  27.                 if (mTranslator != null) {  
  28.                     mTranslator.translateCanvas(canvas);  
  29.                 }  
  30.                 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);  
  31.                 attachInfo.mSetIgnoreDirtyState = false;  
  32.                 //调用View类中的成员方法draw开始绘制View视图  
  33.                 mView.draw(canvas);  
  34.             }   
  35.   
  36.         …………………  
  37.   
  38.         return true;  
  39.     }  
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {

        // Draw with software renderer.
        final Canvas canvas;
        try {
            //从surface对象中获得canvas变量
            canvas = mSurface.lockCanvas(dirty);

            // If this bitmap's format includes an alpha channel, we
            // need to clear it before drawing so that the child will
            // properly re-composite its drawing on a transparent
            // background. This automatically respects the clip/dirty region
            // or
            // If we are applying an offset, we need to clear the area
            // where the offset doesn't appear to avoid having garbage
            // left in the blank areas.
            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
            }

           ......................

            try {
                //调整画布的位置
                canvas.translate(-xoff, -yoff);
                if (mTranslator != null) {
                    mTranslator.translateCanvas(canvas);
                }
                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                attachInfo.mSetIgnoreDirtyState = false;
                //调用View类中的成员方法draw开始绘制View视图
                mView.draw(canvas);
            } 

        .....................

        return true;
    }

分析:代码第8行,从mSurface对象中获得canvas画布,然后将变量canvas变量作为参数传递给第33行代码中的draw方法。由此

可知,我们的视图View最终是绘制到Surface中去的,关于Surface相关的知识,可以参考这篇大神的博客:

Android应用程序窗口(Activity)的绘图表面(Surface)的创建过程分析 

跟踪代码,进入View的draw方法分析源码:

3-2

  1. public void draw(Canvas canvas) {  
  2.         final int privateFlags = mPrivateFlags;  
  3.         final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&  
  4.                 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);  
  5.         mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;  
  6.   
  7.         /* 
  8.          * Draw traversal performs several drawing steps which must be executed 
  9.          * in the appropriate order: 
  10.          * 
  11.          *      1. Draw the background 
  12.          *      2. If necessary, save the canvas’ layers to prepare for fading 
  13.          *      3. Draw view’s content 
  14.          *      4. Draw children 
  15.          *      5. If necessary, draw the fading edges and restore layers 
  16.          *      6. Draw decorations (scrollbars for instance) 
  17.          */  
  18.   
  19.         // Step 1, draw the background, if needed  
  20.         int saveCount;  
  21.   
  22.         if (!dirtyOpaque) {  
  23.             drawBackground(canvas);  
  24.         }  
  25.   
  26.         // skip step 2 & 5 if possible (common case)  
  27.         final int viewFlags = mViewFlags;  
  28.         boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;  
  29.         boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;  
  30.         if (!verticalEdges && !horizontalEdges) {  
  31.             // Step 3, draw the content  
  32.             if (!dirtyOpaque) onDraw(canvas);  
  33.   
  34.             // Step 4, draw the children  
  35.             dispatchDraw(canvas);  
  36.   
  37.             // Step 6, draw decorations (scrollbars)  
  38.             onDrawScrollBars(canvas);  
  39.   
  40.             if (mOverlay != null && !mOverlay.isEmpty()) {  
  41.                 mOverlay.getOverlayView().dispatchDraw(canvas);  
  42.             }  
  43.   
  44.             // we’re done…  
  45.             return;  
  46.         }  
  47.   
  48.         /* 
  49.          * Here we do the full fledged routine… 
  50.          * (this is an uncommon case where speed matters less, 
  51.          * this is why we repeat some of the tests that have been 
  52.          * done above) 
  53.          */  
  54.   
  55.         boolean drawTop = false;  
  56.         boolean drawBottom = false;  
  57.         boolean drawLeft = false;  
  58.         boolean drawRight = false;  
  59.   
  60.         float topFadeStrength = 0.0f;  
  61.         float bottomFadeStrength = 0.0f;  
  62.         float leftFadeStrength = 0.0f;  
  63.         float rightFadeStrength = 0.0f;  
  64.   
  65.         // Step 2, save the canvas’ layers  
  66.         int paddingLeft = mPaddingLeft;  
  67.   
  68.         final boolean offsetRequired = isPaddingOffsetRequired();  
  69.         if (offsetRequired) {  
  70.             paddingLeft += getLeftPaddingOffset();  
  71.         }  
  72.   
  73.         int left = mScrollX + paddingLeft;  
  74.         int right = left + mRight - mLeft - mPaddingRight - paddingLeft;  
  75.         int top = mScrollY + getFadeTop(offsetRequired);  
  76.         int bottom = top + getFadeHeight(offsetRequired);  
  77.   
  78.         if (offsetRequired) {  
  79.             right += getRightPaddingOffset();  
  80.             bottom += getBottomPaddingOffset();  
  81.         }  
  82.   
  83.         final ScrollabilityCache scrollabilityCache = mScrollCache;  
  84.         final float fadeHeight = scrollabilityCache.fadingEdgeLength;  
  85.         int length = (int) fadeHeight;  
  86.   
  87.         // clip the fade length if top and bottom fades overlap  
  88.         // overlapping fades produce odd-looking artifacts  
  89.         if (verticalEdges && (top + length > bottom - length)) {  
  90.             length = (bottom - top) / 2;  
  91.         }  
  92.   
  93.         // also clip horizontal fades if necessary  
  94.         if (horizontalEdges && (left + length > right - length)) {  
  95.             length = (right - left) / 2;  
  96.         }  
  97.   
  98.         if (verticalEdges) {  
  99.             topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));  
  100.             drawTop = topFadeStrength * fadeHeight > 1.0f;  
  101.             bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));  
  102.             drawBottom = bottomFadeStrength * fadeHeight > 1.0f;  
  103.         }  
  104.   
  105.         if (horizontalEdges) {  
  106.             leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));  
  107.             drawLeft = leftFadeStrength * fadeHeight > 1.0f;  
  108.             rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));  
  109.             drawRight = rightFadeStrength * fadeHeight > 1.0f;  
  110.         }  
  111.   
  112.         saveCount = canvas.getSaveCount();  
  113.   
  114.         int solidColor = getSolidColor();  
  115.         if (solidColor == 0) {  
  116.             final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;  
  117.   
  118.             if (drawTop) {  
  119.                 canvas.saveLayer(left, top, right, top + length, null, flags);  
  120.             }  
  121.   
  122.             if (drawBottom) {  
  123.                 canvas.saveLayer(left, bottom - length, right, bottom, null, flags);  
  124.             }  
  125.   
  126.             if (drawLeft) {  
  127.                 canvas.saveLayer(left, top, left + length, bottom, null, flags);  
  128.             }  
  129.   
  130.             if (drawRight) {  
  131.                 canvas.saveLayer(right - length, top, right, bottom, null, flags);  
  132.             }  
  133.         } else {  
  134.             scrollabilityCache.setFadeColor(solidColor);  
  135.         }  
  136.   
  137.         // Step 3, draw the content  
  138.         if (!dirtyOpaque) onDraw(canvas);  
  139.   
  140.         // Step 4, draw the children  
  141.         dispatchDraw(canvas);  
  142.   
  143.         // Step 5, draw the fade effect and restore layers  
  144.         final Paint p = scrollabilityCache.paint;  
  145.         final Matrix matrix = scrollabilityCache.matrix;  
  146.         final Shader fade = scrollabilityCache.shader;  
  147.   
  148.         if (drawTop) {  
  149.             matrix.setScale(1, fadeHeight * topFadeStrength);  
  150.             matrix.postTranslate(left, top);  
  151.             fade.setLocalMatrix(matrix);  
  152.             p.setShader(fade);  
  153.             canvas.drawRect(left, top, right, top + length, p);  
  154.         }  
  155.   
  156.         if (drawBottom) {  
  157.             matrix.setScale(1, fadeHeight * bottomFadeStrength);  
  158.             matrix.postRotate(180);  
  159.             matrix.postTranslate(left, bottom);  
  160.             fade.setLocalMatrix(matrix);  
  161.             p.setShader(fade);  
  162.             canvas.drawRect(left, bottom - length, right, bottom, p);  
  163.         }  
  164.   
  165.         if (drawLeft) {  
  166.             matrix.setScale(1, fadeHeight * leftFadeStrength);  
  167.             matrix.postRotate(-90);  
  168.             matrix.postTranslate(left, top);  
  169.             fade.setLocalMatrix(matrix);  
  170.             p.setShader(fade);  
  171.             canvas.drawRect(left, top, left + length, bottom, p);  
  172.         }  
  173.   
  174.         if (drawRight) {  
  175.             matrix.setScale(1, fadeHeight * rightFadeStrength);  
  176.             matrix.postRotate(90);  
  177.             matrix.postTranslate(right, top);  
  178.             fade.setLocalMatrix(matrix);  
  179.             p.setShader(fade);  
  180.             canvas.drawRect(right - length, top, right, bottom, p);  
  181.         }  
  182.   
  183.         canvas.restoreToCount(saveCount);  
  184.   
  185.         // Step 6, draw decorations (scrollbars)  
  186.         onDrawScrollBars(canvas);  
  187.   
  188.         if (mOverlay != null && !mOverlay.isEmpty()) {  
  189.             mOverlay.getOverlayView().dispatchDraw(canvas);  
  190.         }  
  191.     }  
public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading
         *      3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            // Step 6, draw decorations (scrollbars)
            onDrawScrollBars(canvas);

            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // we're done...
            return;
        }

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }
    }

分析: 
从代码第7-17行可知,视图View的绘制可以分为如下6个步骤:


  1. 绘制当前视图的背景。

  2. 保存当前画布的堆栈状态,并且在在当前画布上创建额外的图层,以便接下来可以用来绘制当前视图在滑动时的边框渐变效果。

  3. 绘制当前视图的内容。

  4. 绘制当前视图的子视图的内容。

  5. 绘制当前视图在滑动时的边框渐变效果。

  6. 绘制当前视图的滚动条。

Step1:绘制视图View的背景 
代码第2-5行,获取当前View是否需要绘制背景的标志dirtyOpaque ,代码第22-24行,根据这个标志来决定是否绘制视图View的背景。如果需要绘制背景,那么进入View类中的drawBackground方法:

  1. /** 
  2.      * Draws the background onto the specified canvas. 
  3.      * 
  4.      * @param canvas Canvas on which to draw the background 
  5.      */  
  6.     private void drawBackground(Canvas canvas) {  
  7.         final Drawable background = mBackground;  
  8.         if (background == null) {  
  9.             return;  
  10.         }  
  11.   
  12.         if (mBackgroundSizeChanged) {  
  13.             background.setBounds(00,  mRight - mLeft, mBottom - mTop);  
  14.             mBackgroundSizeChanged = false;  
  15.             mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;  
  16.         }  
  17.   
  18.        …………  
  19.   
  20.         final int scrollX = mScrollX;  
  21.         final int scrollY = mScrollY;  
  22.         if ((scrollX | scrollY) == 0) {  
  23.             background.draw(canvas);  
  24.         } else {  
  25.             canvas.translate(scrollX, scrollY);  
  26.             background.draw(canvas);  
  27.             canvas.translate(-scrollX, -scrollY);  
  28.         }  
  29.     }  
/**
     * Draws the background onto the specified canvas.
     *
     * @param canvas Canvas on which to draw the background
     */
    private void drawBackground(Canvas canvas) {
        final Drawable background = mBackground;
        if (background == null) {
            return;
        }

        if (mBackgroundSizeChanged) {
            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
            mBackgroundSizeChanged = false;
            mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID;
        }

       ............

        final int scrollX = mScrollX;
        final int scrollY = mScrollY;
        if ((scrollX | scrollY) == 0) {
            background.draw(canvas);
        } else {
            canvas.translate(scrollX, scrollY);
            background.draw(canvas);
            canvas.translate(-scrollX, -scrollY);
        }
    }

该方法用来描述1,绘制当前View的背景的,在绘制背景前,调用background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);方法设置背景的大小,之后调用Drawable的对象backgroud的draw方法完成背景的绘制。

Step2:保存画布canvas的边框参数

代码第27-29获取当前视图View水平或者垂直方向是否需要绘制边框渐变效果,如果不需要绘制边框的渐变效果,就无需执行上面的2,5了。那么就直接执行上面的3,4,6步骤。这里描述的就是我们的ListView滑动到最底端时,底部会有一个淡蓝色的半圆形的边框渐变背景效果。

假如我们需要绘制视图View的边框渐变效果,那么我们继续分析步骤2,3,4,5,6。

代码第55-134行:这段代码用来检查是否需要保存参数canvas所描述的一块画布的堆栈状态,并且创建额外的图层来绘制当前视图在滑动时的边框渐变效果。视图的边框是绘制在内容区域的边界位置上的,而视图的内容区域是需要排除成员变量mPaddingLeft、mPaddingRight、mPaddingTop和mPaddingBottom所描述的视图内边距的。此外,视图的边框有四个,分别位于视图的左、右、上以及下内边界上。因此,这段代码首先需要计算出当前视图的左、右、上以及下内边距的大小,以便得到边框所要绘制的区域。

Step3:绘制视图View的内容

代码第138行我们可以看到,根据条件绘制当前视图View的内容,此处调用了View的成员方法onDraw来绘制视图View的内容,我们来看看onDraw成员方法的实现:

  1. /** 
  2.      * Implement this to do your drawing. 
  3.      * 
  4.      * @param canvas the canvas on which the background will be drawn 
  5.      */  
  6.     protected void onDraw(Canvas canvas) {  
  7.     }  
/**
     * Implement this to do your drawing.
     *
     * @param canvas the canvas on which the background will be drawn
     */
    protected void onDraw(Canvas canvas) {
    }

预料之中,该方法体里面是一个空实现,也就是视图View将绘制的逻辑留给继承它的子类去实现,这也就是为什么我们在自定义View的时候必须去实现其父类的onDraw方法来完成自己对内容的绘制。

Step4:绘制当前视图View的子视图

代码第141行调用View的成员方法dispatchDraw(canvas);来绘制它的子视图,我们进入dispatchDraw(canvas);方法窥探其实现逻辑:

  1. /** 
  2.      * Called by draw to draw the child views. This may be overridden 
  3.      * by derived classes to gain control just before its children are drawn 
  4.      * (but after its own view has been drawn). 
  5.      * @param canvas the canvas on which to draw the view 
  6.      */  
  7.     protected void dispatchDraw(Canvas canvas) {  
  8.   
  9.     }  
/**
     * Called by draw to draw the child views. This may be overridden
     * by derived classes to gain control just before its children are drawn
     * (but after its own view has been drawn).
     * @param canvas the canvas on which to draw the view
     */
    protected void dispatchDraw(Canvas canvas) {

    }

同样你会发现,这也是一个空实现,既然是这样,那么其实现的逻辑也会在它的子类中实现了,由于只有ViewGroup容器才有其子视图,因此,该方法的实现应该在ViewGroup类中,我们进入ViewGroup类中看其源码如下:
  1. @Override  
  2.    protected void dispatchDraw(Canvas canvas) {  
  3.        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);  
  4.        final int childrenCount = mChildrenCount;  
  5.        final View[] children = mChildren;  
  6.        int flags = mGroupFlags;  
  7.        //判断当前ViewGroup容器是否设置的布局动画  
  8.        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {  
  9.            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;  
  10.   
  11.            final boolean buildCache = !isHardwareAccelerated();  
  12.            //遍历给每个子视图View设置动画效果  
  13.            for (int i = 0; i < childrenCount; i++) {  
  14.                final View child = children[i];  
  15.                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {  
  16.                    final LayoutParams params = child.getLayoutParams();  
  17.                    attachLayoutAnimationParameters(child, params, i, childrenCount);  
  18.                    bindLayoutAnimation(child);  
  19.                    if (cache) {  
  20.                        child.setDrawingCacheEnabled(true);  
  21.                        if (buildCache) {  
  22.                            child.buildDrawingCache(true);  
  23.                        }  
  24.                    }  
  25.                }  
  26.            }  
  27.            //获得布局动画的控制器  
  28.            final LayoutAnimationController controller = mLayoutAnimationController;  
  29.            if (controller.willOverlap()) {  
  30.                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;  
  31.            }  
  32.            //开始布局动画  
  33.            controller.start();  
  34.   
  35.            mGroupFlags &= ~FLAG_RUN_ANIMATION;  
  36.            mGroupFlags &= ~FLAG_ANIMATION_DONE;  
  37.   
  38.            if (cache) {  
  39.                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;  
  40.            }  
  41.            //设置布局动画的监听事件  
  42.            if (mAnimationListener != null) {  
  43.                mAnimationListener.onAnimationStart(controller.getAnimation());  
  44.            }  
  45.        }  
  46.   
  47.        int clipSaveCount = 0;  
  48.        //是否需要剪裁边距  
  49.        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;  
  50.        if (clipToPadding) {  
  51.            clipSaveCount = canvas.save();  
  52.            //对画布进行边距剪裁  
  53.            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,  
  54.                    mScrollX + mRight - mLeft - mPaddingRight,  
  55.                    mScrollY + mBottom - mTop - mPaddingBottom);  
  56.        }  
  57.   
  58.        // We will draw our child’s animation, let’s reset the flag  
  59.        mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;  
  60.        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;  
  61.   
  62.        boolean more = false;  
  63.        final long drawingTime = getDrawingTime();  
  64.   
  65.        if (usingRenderNodeProperties) canvas.insertReorderBarrier();  
  66.        // Only use the preordered list if not HW accelerated, since the HW pipeline will do the  
  67.        // draw reordering internally  
  68.        final ArrayList<View> preorderedList = usingRenderNodeProperties  
  69.                ? null : buildOrderedChildList();  
  70.        final boolean customOrder = preorderedList == null  
  71.                && isChildrenDrawingOrderEnabled();  
  72.        //遍历绘制当前视图的子视图View  
  73.        for (int i = 0; i < childrenCount; i++) {  
  74.            int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;  
  75.            final View child = (preorderedList == null)  
  76.                    ? children[childIndex] : preorderedList.get(childIndex);  
  77.            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {  
  78.                more |= drawChild(canvas, child, drawingTime);  
  79.            }  
  80.        }  
  81.        if (preorderedList != null) preorderedList.clear();  
  82.   
  83.        // Draw any disappearing views that have animations  
  84.        if (mDisappearingChildren != null) {  
  85.            final ArrayList<View> disappearingChildren = mDisappearingChildren;  
  86.            final int disappearingCount = disappearingChildren.size() - 1;  
  87.            // Go backwards – we may delete as animations finish  
  88.            for (int i = disappearingCount; i >= 0; i–) {  
  89.                final View child = disappearingChildren.get(i);  
  90.                more |= drawChild(canvas, child, drawingTime);  
  91.            }  
  92.        }  
  93.        if (usingRenderNodeProperties) canvas.insertInorderBarrier();  
  94.   
  95.        if (debugDraw()) {  
  96.            onDebugDraw(canvas);  
  97.        }  
  98.   
  99.        if (clipToPadding) {  
  100.            canvas.restoreToCount(clipSaveCount);  
  101.        }  
  102.   
  103.        // mGroupFlags might have been updated by drawChild()  
  104.        flags = mGroupFlags;  
  105.   
  106.        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {  
  107.            invalidate(true);  
  108.        }  
  109.   
  110.        //更新布局动画的监听事件  
  111.        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&  
  112.                mLayoutAnimationController.isDone() && !more) {  
  113.            // We want to erase the drawing cache and notify the listener after the  
  114.            // next frame is drawn because one extra invalidate() is caused by  
  115.            // drawChild() after the animation is over  
  116.            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;  
  117.            final Runnable end = new Runnable() {  
  118.               public void run() {  
  119.                   notifyAnimationListener();  
  120.               }  
  121.            };  
  122.            post(end);  
  123.        }  
  124.    }  
 @Override
    protected void dispatchDraw(Canvas canvas) {
        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
        final int childrenCount = mChildrenCount;
        final View[] children = mChildren;
        int flags = mGroupFlags;
        //判断当前ViewGroup容器是否设置的布局动画
        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;

            final boolean buildCache = !isHardwareAccelerated();
            //遍历给每个子视图View设置动画效果
            for (int i = 0; i < childrenCount; i++) {
                final View child = children[i];
                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
                    final LayoutParams params = child.getLayoutParams();
                    attachLayoutAnimationParameters(child, params, i, childrenCount);
                    bindLayoutAnimation(child);
                    if (cache) {
                        child.setDrawingCacheEnabled(true);
                        if (buildCache) {
                            child.buildDrawingCache(true);
                        }
                    }
                }
            }
            //获得布局动画的控制器
            final LayoutAnimationController controller = mLayoutAnimationController;
            if (controller.willOverlap()) {
                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
            }
            //开始布局动画
            controller.start();

            mGroupFlags &= ~FLAG_RUN_ANIMATION;
            mGroupFlags &= ~FLAG_ANIMATION_DONE;

            if (cache) {
                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
            }
            //设置布局动画的监听事件
            if (mAnimationListener != null) {
                mAnimationListener.onAnimationStart(controller.getAnimation());
            }
        }

        int clipSaveCount = 0;
        //是否需要剪裁边距
        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
        if (clipToPadding) {
            clipSaveCount = canvas.save();
            //对画布进行边距剪裁
            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
                    mScrollX + mRight - mLeft - mPaddingRight,
                    mScrollY + mBottom - mTop - mPaddingBottom);
        }

        // We will draw our child's animation, let's reset the flag
        mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;
        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;

        boolean more = false;
        final long drawingTime = getDrawingTime();

        if (usingRenderNodeProperties) canvas.insertReorderBarrier();
        // Only use the preordered list if not HW accelerated, since the HW pipeline will do the
        // draw reordering internally
        final ArrayList<View> preorderedList = usingRenderNodeProperties
                ? null : buildOrderedChildList();
        final boolean customOrder = preorderedList == null
                && isChildrenDrawingOrderEnabled();
        //遍历绘制当前视图的子视图View
        for (int i = 0; i < childrenCount; i++) {
            int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
            final View child = (preorderedList == null)
                    ? children[childIndex] : preorderedList.get(childIndex);
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        if (preorderedList != null) preorderedList.clear();

        // Draw any disappearing views that have animations
        if (mDisappearingChildren != null) {
            final ArrayList<View> disappearingChildren = mDisappearingChildren;
            final int disappearingCount = disappearingChildren.size() - 1;
            // Go backwards -- we may delete as animations finish
            for (int i = disappearingCount; i >= 0; i--) {
                final View child = disappearingChildren.get(i);
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        if (usingRenderNodeProperties) canvas.insertInorderBarrier();

        if (debugDraw()) {
            onDebugDraw(canvas);
        }

        if (clipToPadding) {
            canvas.restoreToCount(clipSaveCount);
        }

        // mGroupFlags might have been updated by drawChild()
        flags = mGroupFlags;

        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
            invalidate(true);
        }

        //更新布局动画的监听事件
        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
                mLayoutAnimationController.isDone() && !more) {
            // We want to erase the drawing cache and notify the listener after the
            // next frame is drawn because one extra invalidate() is caused by
            // drawChild() after the animation is over
            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
            final Runnable end = new Runnable() {
               public void run() {
                   notifyAnimationListener();
               }
            };
            post(end);
        }
    }

分析: 
1.代码第8-45行,判断当前ViewGroup布局是否设置了布局动画,如果设置了,则条件满足,给每个子视图View设置布局动画,那么什么情况下,该条件满足呢?当你在布局中使用ViewGroup容器布局,且设置了android:animateLayoutChanges=”true”属性,那么该条件满足,每个子视图View出现的时候都会有一个默认的动画效果。关于容器布局动画,具体详情可以参考我的另外一篇博客:Android属性动画Property Animation系列三之LayoutTransition(布局容器动画) ,这里面详细介绍了布局容器动画的各种使用技巧。

2.代码第49-56行,对当前视图的画布canvas进行边距裁剪,把不需要绘制内容的边距裁剪掉。

3.代码第73-80行,遍历绘制当前容器布局ViewGroup的子视图,其中调用了成员方法drawChild来完成子视图的绘制。

4.代码第83-92行,当子视图设置了消失动画时,遍历绘制布局容器中需要消失的子视图。关于子视图消失动画,具体详情可以参考我的另外一篇博客:Android属性动画Property Animation系列三之LayoutTransition(布局容器动画)

我们现在来分析下ViewGroup中的drawChild方法,看看它是怎么绘制子视图的:

  1. /** 
  2.      * Draw one child of this View Group. This method is responsible for getting 
  3.      * the canvas in the right state. This includes clipping, translating so 
  4.      * that the child’s scrolled origin is at 0, 0, and applying any animation 
  5.      * transformations. 
  6.      * 
  7.      * @param canvas The canvas on which to draw the child 
  8.      * @param child Who to draw 
  9.      * @param drawingTime The time at which draw is occurring 
  10.      * @return True if an invalidate() was issued 
  11.      */  
  12.     protected boolean drawChild(Canvas canvas, View child, long drawingTime) {  
  13.         return child.draw(canvas, this, drawingTime);  
  14.     }  
/**
     * Draw one child of this View Group. This method is responsible for getting
     * the canvas in the right state. This includes clipping, translating so
     * that the child's scrolled origin is at 0, 0, and applying any animation
     * transformations.
     *
     * @param canvas The canvas on which to draw the child
     * @param child Who to draw
     * @param drawingTime The time at which draw is occurring
     * @return True if an invalidate() was issued
     */
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        return child.draw(canvas, this, drawingTime);
    }

是不是预料之中的事情,此处又调用View类中的draw方法来绘制视图,因此形成了一个嵌套调用,知道所有的子视图View绘制结束。到此关于视图View绘制已经基本完成。

Step5:绘制滑动时边框的渐变效果

代码第143-183:绘制当前容器视图ViewGroup的边框渐变效果。

Step6:绘制滚动条

代码第186行:绘制当前视图View的滑动条。此处调用了内部成员方法onDrawScrollBars来绘制滚动条,我们进入源码来窥探一下其如何实现:

  1. protected final void onDrawScrollBars(Canvas canvas) {  
  2.         // scrollbars are drawn only when the animation is running  
  3.         final ScrollabilityCache cache = mScrollCache;  
  4.         //滚动条是否有缓存  
  5.         if (cache != null) {  
  6.   
  7.             int state = cache.state;  
  8.             //滚动条不显示时,直接返回,也就是不绘制滚动条  
  9.             if (state == ScrollabilityCache.OFF) {  
  10.                 return;  
  11.             }  
  12.   
  13.             boolean invalidate = false;  
  14.             //滚动条是否可见  
  15.             if (state == ScrollabilityCache.FADING) {  
  16.                 // We’re fading – get our fade interpolation  
  17.                 if (cache.interpolatorValues == null) {  
  18.                     cache.interpolatorValues = new float[1];  
  19.                 }  
  20.   
  21.                 float[] values = cache.interpolatorValues;  
  22.   
  23.                 // Stops the animation if we’re done  
  24.                 if (cache.scrollBarInterpolator.timeToValues(values) ==  
  25.                         Interpolator.Result.FREEZE_END) {  
  26.                     cache.state = ScrollabilityCache.OFF;  
  27.                 } else {  
  28.                     cache.scrollBar.setAlpha(Math.round(values[0]));  
  29.                 }  
  30.   
  31.                 // This will make the scroll bars inval themselves after  
  32.                 // drawing. We only want this when we’re fading so that  
  33.                 // we prevent excessive redraws  
  34.                 invalidate = true;  
  35.             } else {  
  36.                 // We’re just on – but we may have been fading before so  
  37.                 // reset alpha  
  38.                 //设置滚动条完全可见  
  39.                 cache.scrollBar.setAlpha(255);  
  40.             }  
  41.   
  42.   
  43.             final int viewFlags = mViewFlags;  
  44.   
  45.             final boolean drawHorizontalScrollBar =  
  46.                 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;  
  47.             final boolean drawVerticalScrollBar =  
  48.                 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL  
  49.                 && !isVerticalScrollBarHidden();  
  50.   
  51.             if (drawVerticalScrollBar || drawHorizontalScrollBar) {  
  52.                 final int width = mRight - mLeft;  
  53.                 final int height = mBottom - mTop;  
  54.   
  55.                 final ScrollBarDrawable scrollBar = cache.scrollBar;  
  56.   
  57.                 final int scrollX = mScrollX;  
  58.                 final int scrollY = mScrollY;  
  59.                 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;  
  60.   
  61.                 int left;  
  62.                 int top;  
  63.                 int right;  
  64.                 int bottom;  
  65.                 //绘制水平滚动条  
  66.                 if (drawHorizontalScrollBar) {  
  67.                     int size = scrollBar.getSize(false);  
  68.                     if (size <= 0) {  
  69.                         size = cache.scrollBarSize;  
  70.                     }  
  71.   
  72.                     scrollBar.setParameters(computeHorizontalScrollRange(),  
  73.                                             computeHorizontalScrollOffset(),  
  74.                                             computeHorizontalScrollExtent(), false);  
  75.                     final int verticalScrollBarGap = drawVerticalScrollBar ?  
  76.                             getVerticalScrollbarWidth() : 0;  
  77.                     top = scrollY + height - size - (mUserPaddingBottom & inside);  
  78.                     left = scrollX + (mPaddingLeft & inside);  
  79.                     right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;  
  80.                     bottom = top + size;  
  81.                     onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);  
  82.                     if (invalidate) {  
  83.                         invalidate(left, top, right, bottom);  
  84.                     }  
  85.                 }  
  86.                 //绘制垂直滚动条  
  87.                 if (drawVerticalScrollBar) {  
  88.                     int size = scrollBar.getSize(true);  
  89.                     if (size <= 0) {  
  90.                         size = cache.scrollBarSize;  
  91.                     }  
  92.   
  93.                     scrollBar.setParameters(computeVerticalScrollRange(),  
  94.                                             computeVerticalScrollOffset(),  
  95.                                             computeVerticalScrollExtent(), true);  
  96.                     int verticalScrollbarPosition = mVerticalScrollbarPosition;  
  97.                     if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {  
  98.                         verticalScrollbarPosition = isLayoutRtl() ?  
  99.                                 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;  
  100.                     }  
  101.                     switch (verticalScrollbarPosition) {  
  102.                         default:  
  103.                         case SCROLLBAR_POSITION_RIGHT:  
  104.                             left = scrollX + width - size - (mUserPaddingRight & inside);  
  105.                             break;  
  106.                         case SCROLLBAR_POSITION_LEFT:  
  107.                             left = scrollX + (mUserPaddingLeft & inside);  
  108.                             break;  
  109.                     }  
  110.                     top = scrollY + (mPaddingTop & inside);  
  111.                     right = left + size;  
  112.                     bottom = scrollY + height - (mUserPaddingBottom & inside);  
  113.                     onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);  
  114.                     if (invalidate) {  
  115.                         invalidate(left, top, right, bottom);  
  116.                     }  
  117.                 }  
  118.             }  
  119.         }  
  120.     }  
protected final void onDrawScrollBars(Canvas canvas) {
        // scrollbars are drawn only when the animation is running
        final ScrollabilityCache cache = mScrollCache;
        //滚动条是否有缓存
        if (cache != null) {

            int state = cache.state;
            //滚动条不显示时,直接返回,也就是不绘制滚动条
            if (state == ScrollabilityCache.OFF) {
                return;
            }

            boolean invalidate = false;
            //滚动条是否可见
            if (state == ScrollabilityCache.FADING) {
                // We're fading -- get our fade interpolation
                if (cache.interpolatorValues == null) {
                    cache.interpolatorValues = new float[1];
                }

                float[] values = cache.interpolatorValues;

                // Stops the animation if we're done
                if (cache.scrollBarInterpolator.timeToValues(values) ==
                        Interpolator.Result.FREEZE_END) {
                    cache.state = ScrollabilityCache.OFF;
                } else {
                    cache.scrollBar.setAlpha(Math.round(values[0]));
                }

                // This will make the scroll bars inval themselves after
                // drawing. We only want this when we're fading so that
                // we prevent excessive redraws
                invalidate = true;
            } else {
                // We're just on -- but we may have been fading before so
                // reset alpha
                //设置滚动条完全可见
                cache.scrollBar.setAlpha(255);
            }


            final int viewFlags = mViewFlags;

            final boolean drawHorizontalScrollBar =
                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
            final boolean drawVerticalScrollBar =
                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
                && !isVerticalScrollBarHidden();

            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
                final int width = mRight - mLeft;
                final int height = mBottom - mTop;

                final ScrollBarDrawable scrollBar = cache.scrollBar;

                final int scrollX = mScrollX;
                final int scrollY = mScrollY;
                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;

                int left;
                int top;
                int right;
                int bottom;
                //绘制水平滚动条
                if (drawHorizontalScrollBar) {
                    int size = scrollBar.getSize(false);
                    if (size <= 0) {
                        size = cache.scrollBarSize;
                    }

                    scrollBar.setParameters(computeHorizontalScrollRange(),
                                            computeHorizontalScrollOffset(),
                                            computeHorizontalScrollExtent(), false);
                    final int verticalScrollBarGap = drawVerticalScrollBar ?
                            getVerticalScrollbarWidth() : 0;
                    top = scrollY + height - size - (mUserPaddingBottom & inside);
                    left = scrollX + (mPaddingLeft & inside);
                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
                    bottom = top + size;
                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
                    if (invalidate) {
                        invalidate(left, top, right, bottom);
                    }
                }
                //绘制垂直滚动条
                if (drawVerticalScrollBar) {
                    int size = scrollBar.getSize(true);
                    if (size <= 0) {
                        size = cache.scrollBarSize;
                    }

                    scrollBar.setParameters(computeVerticalScrollRange(),
                                            computeVerticalScrollOffset(),
                                            computeVerticalScrollExtent(), true);
                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
                        verticalScrollbarPosition = isLayoutRtl() ?
                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
                    }
                    switch (verticalScrollbarPosition) {
                        default:
                        case SCROLLBAR_POSITION_RIGHT:
                            left = scrollX + width - size - (mUserPaddingRight & inside);
                            break;
                        case SCROLLBAR_POSITION_LEFT:
                            left = scrollX + (mUserPaddingLeft & inside);
                            break;
                    }
                    top = scrollY + (mPaddingTop & inside);
                    right = left + size;
                    bottom = scrollY + height - (mUserPaddingBottom & inside);
                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
                    if (invalidate) {
                        invalidate(left, top, right, bottom);
                    }
                }
            }
        }
    }

分析: 
1.代码第9行,判断是否需要绘制当前视图View的滚动条。如果你给当前视图View设置了android:scrollbars=”none”属性,时就不会绘制滚动条,也就是不显示滚动条。

2.代码第15行,判断当前视图View的滚动条是否可消失。如果你给当前视图View设置了android:fadeScrollbars=”true”属性时,你不滑动,滚动条隐藏,你滑动时,滚动条显示,有代码可以看出,此处是通过改变滚动条的透明度来实现滚动条隐藏和显示的。

3.代码第35-39行,当前视图View的滚动条设置成完全可见,也就是你设置了该属性android:fadeScrollbars=”false”。不管你是否滑动View,滚动条一直可见。

4.代码第43-116行,都是绘制水平或者垂直滚动条的逻辑。

至此,视图View的整个绘制流程就结束了。最后上一张绘制流程图如下:


绘制Draw总结:

1.View绘制的画布参数canvas是由surface对象获得,言外之意,View视图绘制最终会绘制到Surface对象去。关于Surface内容参考3-1节。

2.由3-2小节我们了解到,父类View绘制主要是绘制背景,边框渐变效果,进度条,View具体的内容绘制调用了onDraw方法,通过该方法把View内容的绘制逻辑留给子类去实现。因此,我们在自定义View的时候都一般都需要重写父类的onDraw方法来实现View内容绘制。

3.不管任何情况,每一个View视图都会绘制 scrollBars滚动条,且绘制滚动条的逻辑是在父类View中实现,子类无需自己实现滚动条的绘制。其实TextView也是有滚动条的,可以通过代码让其显示滚动条和内容滚动效果。你只需在TextView布局设置android:scrollbars=”vertical”属性,且在代码中进行如下设置

  1. textView.setMovementMethod(ScrollingMovementMethod.getInstance());   
textView.setMovementMethod(ScrollingMovementMethod.getInstance()); 

这样既可让你的TextView内容可以滑动,且有滚动条。

4.ViewGroup绘制的过程会对每个子视图View设置布局容器动画效果,如果你在ViewGroup容器布局里面设置了如下属性的话:

  1. android:animateLayoutChanges=“true”  
android:animateLayoutChanges="true"

总结:

通过以上分析:视图View的绘制流程基本了解清楚,主要分三个步骤:measure测量,layout布局,draw绘制。当然这三个步骤并不是都要执行,在执行每一步之前都会判断当前视图是否需要重新measure测量,是否需要重新layout布局,是否需要重新draw绘制。其中很多细节性的东西,望有意了解者可以自己跟着源码思路自己分析一遍,以便自己完全理解。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值