澳门新葡萄京官网注册 2

澳门新葡萄京官网注册Android Bitmap 知识点梳理

创建Window

在Activity的attach方法中通过调用PolicyManager.makeNewWindo创建Window,将一个View
add到WindowManager时,WindowManagerImpl创建一个ViewRoot来管理该窗口的根View。并通过ViewRoot.setView方法把该View传给ViewRoot。

final void attach(Context context, ActivityThread aThread,  
        Instrumentation instr, IBinder token, int ident,  
        Application application, Intent intent, ActivityInfo info,  
        CharSequence title, Activity parent, String id,  
        NonConfigurationInstances lastNonConfigurationInstances,  
        Configuration config) {  
    attachBaseContext(context);  

    mFragments.attachActivity(this, mContainer, null);  

    mWindow = PolicyManager.makeNewWindow(this);  
    mWindow.setCallback(this);  
    mWindow.getLayoutInflater().setPrivateFactory(this);

View绘制基本流程

Android系统View的绘制流程:依次执行View类里面的如下三个方法:
measure(int ,int) :测量View的大小

layout(int ,int ,int ,int) :设置子View的位置

draw(Canvas) :绘制View内容到Canvas画布上

整个View树的绘图流程是在ViewRoot.Java类的performTraversals()函数展开的,该函数做的执行过程可简单概况为根据之前设置的状态,判断是否需要重新计算视图大小(measure)、是否重新需要安置视图的位置(layout)、以及是否需要重绘
(draw)

这是我在学习android
自定义UI控件时的一些瓶颈,现在琳琅满目的各种UI控件,其实让很多开发者感觉很便利。但要写出不同的高效控件和复杂动画,抄抄写写是不行的,须先理解android
View 的绘制过程。

创建DecorView

DecorView为整个Window界面的最顶层View。

Activity中的Window对象帮我们创建了一个PhoneWindow内部类DecorView(父类为FrameLayout)窗口顶层视图,然后通过LayoutInflater将xml内容布局解析成View树形结构添加到DecorView顶层视图中id为content的FrameLayout父容器上面。Activity的content内容布局最终会添加到DecorView窗口顶层视图上面。

protected boolean initializePanelDecor(PanelFeatureState st) {  
    st.decorView = new DecorView(getContext(), st.featureId);  
    st.gravity = Gravity.CENTER | Gravity.BOTTOM;  
    st.setStyle(getContext());  

    return true;  
}

mesarue()测量过程

主要作用:为整个View树计算实际的大小,即设置实际的高(mMeasuredHeight)和宽(mMeasureWidth),每个View的控件的实际宽高都是由父视图和本身视图决定的。

具体的调用如下:

ViewRootImpl
的performTraversals方法中,调用measureHierarchy,然后调用performMeasure

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {  
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");  
       try {  
           mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
       } finally {  
           Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
       }  
       }

澳门新葡萄京官网注册,ViewRoot根对象地属性mView(其类型一般为ViewGroup类型)调用measure()方法去计算View树的大小,回调View/ViewGroup对象的onMeasure()方法,该方法实现的功能如下:

1、设置本View视图的最终大小,该功能的实现通过调用setMeasuredDimension()方法去设置实际的高(mMeasuredHeight)和宽(mMeasureWidth)

2、如果该View对象是个ViewGroup类型,需要重写onMeasure()方法,对其子视图进行遍历的measure()过程。

对每个子视图的measure()过程,是通过调用父类ViewGroup.java类里的measureChildWithMargins()方法去实现,该方法内部只是简单地调用了View对象的measure()方法。

整个measure调用流程就是个树形的递归过程measure()方法两个参数都是父View传递过来的,也就是代表了父view的规格。他由两部分组成,高2位表示MODE,定义在MeasureSpec类(View的内部类)中,有三种类型,MeasureSpec.EXACTLY表示确定大小,
MeasureSpec.AT_MOST表示最大大小,
MeasureSpec.UNSPECIFIED不确定。低30位表示size,也就是父View的大小。对于系统Window类的DecorVIew对象Mode一般都为MeasureSpec.EXACTLY
,而size分别对应屏幕宽高。对于子View来说大小是由父View和子View共同决定的。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
        getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
}

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
 boolean optical = isLayoutModeOptical(this);  
 if (optical != isLayoutModeOptical(mParent)) {  
     Insets insets = getOpticalInsets();  
     int opticalWidth  = insets.left + insets.right;  
     int opticalHeight = insets.top  + insets.bottom;  

     measuredWidth  += optical ? opticalWidth  : -opticalWidth;  
     measuredHeight += optical ? opticalHeight : -opticalHeight;  
 }  
 mMeasuredWidth = measuredWidth;  
 mMeasuredHeight = measuredHeight;  

 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;  
 }

1.View的遍历过程

整个View树的绘图流程是在ViewRoot.java类的performTraversals()函数展开的,该函数做的执行过程可简单概况为

根据之前设置的状态,判断是否需要重新计算视图大小(measure)、是否重新需要安置视图的位置(layout)、以及是否需要重绘

(draw),其框架过程如下:

澳门新葡萄京官网注册 1

Paste_Image.png

performTraversals函数,具体的可以参考一下源代码:

private void performTraversals() {  
    final View host = mView;  
    ...  
    host.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
    ...  
    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  
    ...  
    draw(fullRedrawNeeded);  

可以看出View的主要绘制经历三个过程:Measure、Layout、Draw。

创建ViewRoot并关联View

WindowManagerImpl保存DecorView到mViews,创建对应的ViewRoot;

ViewRoot用于管理窗口的根View,并和global window
manger进行交互。ViewRoot中有一个nested class:
W,W是一个Binder子类,用于接收global window manager的各种消息,
如按键消息, 触摸消息等。
ViewRoot有一个W类型的成员mWindow,ViewRoot在Constructor中创建一个W的instance并赋值给mWindow。
ViewRoot是Handler的子类, W会通过Looper把消息传递给ViewRoot。
ViewRoot在setView方法中把mWindow传给sWindowSession。

public void addView(View view, ViewGroup.LayoutParams params,  
        Display display, Window parentWindow) {  
    if (view == null) {  
        throw new IllegalArgumentException("view must not be null");  
    }  
    if (display == null) {  
        throw new IllegalArgumentException("display must not be null");  
    }  
    if (!(params instanceof WindowManager.LayoutParams)) {  
        throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");  
    }  

    final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;  
    if (parentWindow != null) {  
        parentWindow.adjustLayoutParamsForSubWindow(wparams);  
    }  

    ViewRootImpl root;  
    View panelParentView = null;  

    synchronized (mLock) {  
        // Start watching for system property changes.  
        if (mSystemPropertyUpdater == null) {  
            mSystemPropertyUpdater = new Runnable() {  
                @Override public void run() {  
                    synchronized (mLock) {  
                        for (ViewRootImpl viewRoot : mRoots) {  
                            viewRoot.loadSystemProperties();  
                        }  
                    }  
                }  
            };  
            SystemProperties.addChangeCallback(mSystemPropertyUpdater);  
        }  

        int index = findViewLocked(view, false);  
        if (index >= 0) {  
            throw new IllegalStateException("View " + view  
                    + " has already been added to the window manager.");  
        }  

        // If this is a panel window, then find the window it is being  
        // attached to for future reference.  
        if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&  
                wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {  
            final int count = mViews != null ? mViews.length : 0;  
            for (int i=0; i<count; i++) {  
                if (mRoots[i].mWindow.asBinder() == wparams.token) {  
                    panelParentView = mViews[i];  
                }  
            }  
        }  

        root = new ViewRootImpl(view.getContext(), display);  

        view.setLayoutParams(wparams);  

        if (mViews == null) {  
            index = 1;  
            mViews = new View[1];  
            mRoots = new ViewRootImpl[1];  
            mParams = new WindowManager.LayoutParams[1];  
        } else {  
            index = mViews.length + 1;  
            Object[] old = mViews;  
            mViews = new View[index];  
            System.arraycopy(old, 0, mViews, 0, index-1);  
            old = mRoots;  
            mRoots = new ViewRootImpl[index];  
            System.arraycopy(old, 0, mRoots, 0, index-1);  
            old = mParams;  
            mParams = new WindowManager.LayoutParams[index];  
            System.arraycopy(old, 0, mParams, 0, index-1);  
        }  
        index--;  

        mViews[index] = view;  
        mRoots[index] = root;  
        mParams[index] = wparams;  
    }  

    // do this last because it fires off messages to start doing things  
    try {  
        root.setView(view, wparams, panelParentView);  
    } catch (RuntimeException e) {  
        // BadTokenException or InvalidDisplayException, clean up.  
        synchronized (mLock) {  
            final int index = findViewLocked(view, false);  
            if (index >= 0) {  
                removeViewLocked(index, true);  
            }  
        }  
        throw e;  
    }  
}

ViewRoot是GUI管理系统与GUI呈现系统之间的桥梁,需要注意它并不是一个View类型。

它的主要作用如下:

1、向DecorView分发收到的用户发起的event事件,如按键,触屏,轨迹球等事件;
2、与WindowManagerService交互,完成整个Activity的GUI的绘制。

layout布局过程

主要作用
:为将整个根据子视图的大小以及布局参数将View树放到合适的位置上。

具体的调用如下:

ViewRootImpl 的performTraversals方法中,调用performLayout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,  
    int desiredWindowHeight) {  
mLayoutRequested = false;  
mScrollMayChange = true;  
mInLayout = true;  

final View host = mView;  
if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {  
    Log.v(TAG, "Laying out " + host + " to (" +  
            host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");  
}  

Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");  
try {  
    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

    mInLayout = false;  
    int numViewsRequestingLayout = mLayoutRequesters.size();  
    if (numViewsRequestingLayout > 0) {  
        // requestLayout() was called during layout.  
        // If no layout-request flags are set on the requesting views, there is no problem.  
        // If some requests are still pending, then we need to clear those flags and do  
        // a full request/measure/layout pass to handle this situation.  
        ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,  
                false);  
        if (validLayoutRequesters != null) {  
            // Set this flag to indicate that any further requests are happening during  
            // the second pass, which may result in posting those requests to the next  
            // frame instead  
            mHandlingLayoutInLayoutRequest = true;  

            // Process fresh layout requests, then measure and layout  
            int numValidRequests = validLayoutRequesters.size();  
            for (int i = 0; i < numValidRequests; ++i) {  
                final View view = validLayoutRequesters.get(i);  
                Log.w("View", "requestLayout() improperly called by " + view +  
                        " during layout: running second layout pass");  
                view.requestLayout();  
            }  
            measureHierarchy(host, lp, mView.getContext().getResources(),  
                    desiredWindowWidth, desiredWindowHeight);  
            mInLayout = true;  
            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

            mHandlingLayoutInLayoutRequest = false;  

            // Check the valid requests again, this time without checking/clearing the  
            // layout flags, since requests happening during the second pass get noop'd  
            validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);  
            if (validLayoutRequesters != null) {  
                final ArrayList<View> finalRequesters = validLayoutRequesters;  
                // Post second-pass requests to the next frame  
                getRunQueue().post(new Runnable() {  
                    @Override  
                    public void run() {  
                        int numValidRequests = finalRequesters.size();  
                        for (int i = 0; i < numValidRequests; ++i) {  
                            final View view = finalRequesters.get(i);  
                            Log.w("View", "requestLayout() improperly called by " + view +  
                                    " during second layout pass: posting in next frame");  
                            view.requestLayout();  
                        }  
                    }  
                });  
            }  
        }  

    }  
} finally {  
    Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
}  
mInLayout = false;  

}

1.mesarue()过程

为整个View树计算实际的大小,即设置实际的高(对应属性:mMeasuredHeight)和宽(对应属性:
mMeasureWidth),每个View的控件的实际宽高都是由父视图和本身视图决定的。
具体的调用链如下:
ViewRoot根对象地属性mView(其类型一般为ViewGroup类型)调用measure()方法去计算View树的大小,回调View/ViewGroup对象的onMeasure()方法,该方法实现的功能如下:
1、设置本View视图的最终大小,该功能的实现通过调用setMeasuredDimension()方法去设置实际的高(对应属性:
mMeasuredHeight)和宽(对应属性:mMeasureWidth);
2
、如果该View对象是个ViewGroup类型,需要重写该onMeasure()方法,对其子视图进行遍历的measure()过程;
3、
对每个子视图的measure()过程,是通过调用父类ViewGroup.java类里的measureChildWithMargins()方法去实现,该方法内部只是简单地调用了View对象的measure()方法。(由于measureChildWithMargins()方法只是一个过渡层更简单的做法是直接调用View对象的measure()方法)。整个measure调用流程就是个树形的递归过程

** measure函数原型为 View.java 该函数不能被重载**
来看代码,主要方法有:

public final void measure(int widthMeasureSpec, int heightMeasureSpec)  
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  

measure调用onMeasure,onMeasure调用setMeasureDimension,measure,setMeasureDimension是final类型,view的子类不需要重写,onMeasure在view的子类中重写。

View绘制基本流程

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

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

澳门新葡萄京官网注册 2

整个View树的绘图流程是在ViewRoot.Java类的performTraversals()函数展开的,该函数做的执行过程可简单概况为根据之前设置的状态,判断是否需要重新计算视图大小(measure)、是否重新需要安置视图的位置(layout)、以及是否需要重绘
(draw)

draw()绘图过程

ViewRootImpl 的performTraversals方法中,调用了mView的draw方法

mView.draw()开始绘制,draw()方法实现的功能如下:

1 、绘制该View的背景

2 、为显示渐变框做一些准备操作

3、调用onDraw()方法绘制视图本身
(每个View都需要重载该方法,ViewGroup不需要实现该方法)

4、调用dispatchDraw
()方法绘制子视图(如果该View类型不为ViewGroup,即不包含子视图,不需要重载该方法)

值得说明的是,ViewGroup类已经为我们重写了dispatchDraw
()的功能实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能。

dispatchDraw()方法内部会遍历每个子视图,调用drawChild()去重新回调每个子视图的draw()方法。

measure函数:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {  
    if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||  
            widthMeasureSpec != mOldWidthMeasureSpec ||  
            heightMeasureSpec != mOldHeightMeasureSpec) {  

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

        if (ViewDebug.TRACE_HIERARCHY) {  
            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);  
        }  

        // measure ourselves, this should set the measured dimension flag back  
        onMeasure(widthMeasureSpec, heightMeasureSpec);  

        // flag not set, setMeasuredDimension() was not invoked, we raise  
        // an exception to warn the developer  
        if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {  
            throw new IllegalStateException("onMeasure() did not set the"  
                    + " measured dimension by calling"  
                    + " setMeasuredDimension()");  
        }  

        mPrivateFlags |= LAYOUT_REQUIRED;  
    }  

    mOldWidthMeasureSpec = widthMeasureSpec;  
    mOldHeightMeasureSpec = heightMeasureSpec;  
}  

 mesarue()测量过程

主要作用:为整个View树计算实际的大小,即设置实际的高(mMeasuredHeight)和宽(mMeasureWidth),每个View的控件的实际宽高都是由父视图和本身视图决定的。

具体的调用如下:

ViewRootImpl
的performTraversals方法中,调用measureHierarchy,然后调用performMeasure

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {  
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");  
       try {  
           mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
       } finally {  
           Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
       }  
   }

ViewRoot根对象地属性mView(其类型一般为ViewGroup类型)调用measure()方法去计算View树的大小,回调View/ViewGroup对象的onMeasure()方法,该方法实现的功能如下:

1、设置本View视图的最终大小,该功能的实现通过调用setMeasuredDimension()方法去设置实际的高(mMeasuredHeight)和宽(mMeasureWidth)

2、如果该View对象是个ViewGroup类型,需要重写onMeasure()方法,对其子视图进行遍历的measure()过程。

对每个子视图的measure()过程,是通过调用父类ViewGroup.java类里的measureChildWithMargins()方法去实现,该方法内部只是简单地调用了View对象的measure()方法。

整个measure调用流程就是个树形的递归过程measure()方法两个参数都是父View传递过来的,也就是代表了父view的规格。他由两部分组成,高2位表示MODE,定义在MeasureSpec类(View的内部类)中,有三种类型,MeasureSpec.EXACTLY表示确定大小,
MeasureSpec.AT_MOST表示最大大小,
MeasureSpec.UNSPECIFIED不确定。低30位表示size,也就是父View的大小。对于系统Window类的DecorVIew对象Mode一般都为MeasureSpec.EXACTLY
,而size分别对应屏幕宽高。对于子View来说大小是由父View和子View共同决定的。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
}

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
     boolean optical = isLayoutModeOptical(this);  
     if (optical != isLayoutModeOptical(mParent)) {  
         Insets insets = getOpticalInsets();  
         int opticalWidth  = insets.left + insets.right;  
         int opticalHeight = insets.top  + insets.bottom;  

         measuredWidth  += optical ? opticalWidth  : -opticalWidth;  
         measuredHeight += optical ? opticalHeight : -opticalHeight;  
     }  
     mMeasuredWidth = measuredWidth;  
     mMeasuredHeight = measuredHeight;  

     mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;  
 }

5、绘制滚动条

刷新视图

Android中实现view的更新有两个方法,一个是invalidate,另一个是postInvalidate,其中前者是在UI线程自身中使用,而后者在非UI线程中使用。

requestLayout()方法 :会导致调用measure()过程 和 layout()过程 。

说明:只是对View树重新布局layout过程包括measure()和layout()过程,不会调用draw()过程,但不会重新绘制
任何视图包括该调用者本身。
一般引起invalidate()操作的函数如下:

1、直接调用invalidate()方法,请求重新draw(),但只会绘制调用者本身。

2、setSelection()方法 :请求重新draw(),但只会绘制调用者本身。

3、setVisibility()方法 :
当View可视状态在INVISIBLE转换VISIBLE时,会间接调用invalidate()方法,继而绘制该View。

4 、setEnabled()方法 :
请求重新draw(),但不会重新绘制任何视图包括该调用者本身。

onMeasure函数:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
}  

重写onMeasure时,要调用setMeasuredDimension或者super.onMeasure来设置自身的mMeasuredWidth和mMeasuredHeight,否则,就会抛出异常.
setMeasuredDimension函数,用来设置view的大小:

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
    mMeasuredWidth = measuredWidth;  
    mMeasuredHeight = measuredHeight;  

    mPrivateFlags |= MEASURED_DIMENSION_SET;  
}  

再看一下onMeasure的

layout布局过程

主要作用
:为将整个根据子视图的大小以及布局参数将View树放到合适的位置上。

具体的调用如下:

ViewRootImpl 的performTraversals方法中,调用performLayout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,  
        int desiredWindowHeight) {  
    mLayoutRequested = false;  
    mScrollMayChange = true;  
    mInLayout = true;  

    final View host = mView;  
    if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {  
        Log.v(TAG, "Laying out " + host + " to (" +  
                host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");  
    }  

    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");  
    try {  
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

        mInLayout = false;  
        int numViewsRequestingLayout = mLayoutRequesters.size();  
        if (numViewsRequestingLayout > 0) {  
            // requestLayout() was called during layout.  
            // If no layout-request flags are set on the requesting views, there is no problem.  
            // If some requests are still pending, then we need to clear those flags and do  
            // a full request/measure/layout pass to handle this situation.  
            ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,  
                    false);  
            if (validLayoutRequesters != null) {  
                // Set this flag to indicate that any further requests are happening during  
                // the second pass, which may result in posting those requests to the next  
                // frame instead  
                mHandlingLayoutInLayoutRequest = true;  

                // Process fresh layout requests, then measure and layout  
                int numValidRequests = validLayoutRequesters.size();  
                for (int i = 0; i < numValidRequests; ++i) {  
                    final View view = validLayoutRequesters.get(i);  
                    Log.w("View", "requestLayout() improperly called by " + view +  
                            " during layout: running second layout pass");  
                    view.requestLayout();  
                }  
                measureHierarchy(host, lp, mView.getContext().getResources(),  
                        desiredWindowWidth, desiredWindowHeight);  
                mInLayout = true;  
                host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

                mHandlingLayoutInLayoutRequest = false;  

                // Check the valid requests again, this time without checking/clearing the  
                // layout flags, since requests happening during the second pass get noop'd  
                validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);  
                if (validLayoutRequesters != null) {  
                    final ArrayList<View> finalRequesters = validLayoutRequesters;  
                    // Post second-pass requests to the next frame  
                    getRunQueue().post(new Runnable() {  
                        @Override  
                        public void run() {  
                            int numValidRequests = finalRequesters.size();  
                            for (int i = 0; i < numValidRequests; ++i) {  
                                final View view = finalRequesters.get(i);  
                                Log.w("View", "requestLayout() improperly called by " + view +  
                                        " during second layout pass: posting in next frame");  
                                view.requestLayout();  
                            }  
                        }  
                    });  
                }  
            }  

        }  
    } finally {  
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
    }  
    mInLayout = false;  
}

host.layout()开始View树的布局,继而回调给View/ViewGroup类中的layout()方法。具体流程如下

1
、layout方法会设置该View视图位于父视图的坐标轴,即mLeft,mTop,mLeft,mBottom(调用setFrame()函数去实现),接下来回调onLayout()方法(如果该View是ViewGroup对象,需要实现该方法,对每个子视图进行布局)。

2、如果该View是个ViewGroup类型,需要遍历每个子视图chiildView,调用该子视图的layout()方法去设置它的坐标值。

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
}

public void layout(int l, int t, int r, int b) {  
    int oldL = mLeft;  
    int oldT = mTop;  
    int oldB = mBottom;  
    int oldR = mRight;  
    boolean changed = isLayoutModeOptical(mParent) ?  
            setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);  
    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {  
        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;  
}

getDefaultSize函数:

public static int getDefaultSize(int size, int measureSpec) {  
    int result = size;  
    int specMode = MeasureSpec.getMode(measureSpec);  
    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;  
} 

这里用引入了
MeasureSpec类:

public static class MeasureSpec {  

    private static final int MODE_SHIFT = 30;  
    private static final int MODE_MASK  = 0x3 << MODE_SHIFT;  
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;  
    public static final int EXACTLY     = 1 << MODE_SHIFT;  
    public static final int AT_MOST     = 2 << MODE_SHIFT;  

    public static int makeMeasureSpec(int size, int mode) {  
        return size + mode;  
    }  

    public static int getMode(int measureSpec) {  
        return (measureSpec & MODE_MASK);  
    }  

    public static int getSize(int measureSpec) {  
        return (measureSpec & ~MODE_MASK);  
    }  
}  

MODE_MASK为30为长度的二进制数,前两位标示Mode,后面的标示Size。MeasureSpec有三种模式分别是UNSPECIFIED,
EXACTLY和AT_MOST。
EXACTLY表示父视图希望子视图的大小应该是由specSize的值来决定的,系统默认会按照这个规则来设置子视图的大小,开发人员当然也可以按照自己的意愿设置成任意的大小。
AT_MOST表示子视图最多只能是specSize中指定的大小,开发人员应该尽可能小得去设置这个视图,并且保证不会超过specSize。系统默认会按照这个规则来设置子视图的大小,开发人员当然也可以按照自己的意愿设置成任意的大小。
UNSPECIFIED表示开发人员可以将视图按照自己的意愿设置成任意的大小,没有任何限制。这种情况比较少见,不太会用到。
widthMeasureSpec和heightMeasureSpec决定了Mode和Size的值,widthMeasureSpec和heightMeasureSpec来自父视图,这两个值都是由父视图经过计算后传递给子视图的,说明父视图会在一定程度上决定子视图的大小。但是最外层的根视图,它的widthMeasureSpec和heightMeasureSpec又是从哪里得到的呢?这就需要去分析ViewRoot中的源码了,观察performTraversals()方法可以发现如下代码:

childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);  
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); 

可以看到,这里调用了getRootMeasureSpec()方法去获取widthMeasureSpec和heightMeasureSpec的值,注意方法中传入的参数,其中lp.width和lp.height在创建ViewGroup实例的时候就被赋值了,它们都等于MATCH_PARENT。然后看下getRootMeasureSpec()方法中的代码,如下所示:

private int getRootMeasureSpec(int windowSize, int rootDimension) {  
    int measureSpec;  
    switch (rootDimension) {  
    case ViewGroup.LayoutParams.MATCH_PARENT:  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);  
        break;  
    case ViewGroup.LayoutParams.WRAP_CONTENT:  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);  
        break;  
    default:  
        measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);  
        break;  
    }  
    return measureSpec;  
}  

可以看到,这里使用了MeasureSpec.makeMeasureSpec()方法来组装一个MeasureSpec,当rootDimension参数等于MATCH_PARENT的时候,MeasureSpec的specMode就等于EXACTLY,当rootDimension等于WRAP_CONTENT的时候,MeasureSpec的specMode就等于AT_MOST。并且MATCH_PARENT和WRAP_CONTENT时的specSize都是等于windowSize的,也就意味着根视图总是会充满全屏的。

Measure是一个复杂的过程,因为一个布局中一般都会包含多个子视图,每个视图都需要经历一次measure过程。ViewGroup中定义了一个measureChildren()方法来去测量子视图的大小,如下所示:

draw()绘图过程

ViewRootImpl 的performTraversals方法中,调用了mView的draw方法

mView.draw()开始绘制,draw()方法实现的功能如下:

1 、绘制该View的背景
2 、为显示渐变框做一些准备操作
3、调用onDraw()方法绘制视图本身  
(每个View都需要重载该方法,ViewGroup不需要实现该方法)
4、调用dispatchDraw
()方法绘制子视图(如果该View类型不为ViewGroup,即不包含子视图,不需要重载该方法)

值得说明的是,ViewGroup类已经为我们重写了dispatchDraw
()的功能实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能。

dispatchDraw()方法内部会遍历每个子视图,调用drawChild()去重新回调每个子视图的draw()方法。

5、绘制滚动条

measureChildren函数:

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {  
       final int size = mChildrenCount;  
       final View[] children = mChildren;  
       for (int i = 0; i < size; ++i) {  
           final View child = children[i];  
           if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {  
               measureChild(child, widthMeasureSpec, heightMeasureSpec);  
           }  
       }  
   } 

这里会去遍历当前布局下的所有子视图,然后逐个调用measureChild()方法来测量相应子视图的大小:

刷新视图

Android中实现view的更新有两个方法,一个是invalidate,另一个是postInvalidate,其中前者是在UI线程自身中使用,而后者在非UI线程中使用。

requestLayout()方法 :会导致调用measure()过程 和 layout()过程 。

说明:只是对View树重新布局layout过程包括measure()和layout()过程,不会调用draw()过程,但不会重新绘制
任何视图包括该调用者本身。
一般引起invalidate()操作的函数如下:

1、直接调用invalidate()方法,请求重新draw(),但只会绘制调用者本身。

2、setSelection()方法 :请求重新draw(),但只会绘制调用者本身。

3、setVisibility()方法 :
当View可视状态在INVISIBLE转换VISIBLE时,会间接调用invalidate()方法,继而绘制该View。

4 、setEnabled()方法 :
请求重新draw(),但不会重新绘制任何视图包括该调用者本身。

内容参考源码,借鉴了网上的一些分析。

measureChild函数:

protected void measureChild(View child, int parentWidthMeasureSpec,  
           int parentHeightMeasureSpec) {  
       final LayoutParams lp = child.getLayoutParams();  

       final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,  
               mPaddingLeft + mPaddingRight, lp.width);  
       final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,  
               mPaddingTop + mPaddingBottom, lp.height);  

       child.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
   }  

从这里我们可以看到视图的大小是由父视图和子视图共同决定的。子布局里面的Android:layout_width和android:layout_height只是期望值,父View大小最终是由DecorView决定。父视图提供尺寸大小的一个能力,子视图最终尺寸与父视图能力、子视图期望的关系如下:

父视图能力尺寸 子视图期望尺寸 子视图最终允许尺寸
EXACTLY + Size1 EXACTLY + Size2 EXACTLY + Size2
EXACTLY + Size1 fill_parent/match_parent EXACTLY+Size1
EXACTLY + Size1 wrap_content AT_MOST+Size1
AT_MOST+Size1 EXACTLY + Size2 EXACTLY+Size2
AT_MOST+Size1 fill_parent/match_parent AT_MOST+Size1
AT_MOST+Size1 wrap_content AT_MOST+Size1
UNSPECIFIED+Size1 EXACTLY + Size2 EXACTLY + Size2
UNSPECIFIED+Size1 fill_parent/match_parent UNSPECIFIED+0
UNSPECIFIED+Size1 wrap_content UNSPECIFIED+0

关于视图的measure过程可以阅读以下LinearLayout源码,这样可以更清楚的了解过程。

2.Layout过程

measure过程确定视图的大小,而layout过程确定视图的位置。
主要作用
:为将整个根据子视图的大小以及布局参数将View树放到合适的位置上。具体的调用是:host.layout()开始View树的布局,继而回调给View/ViewGroup类中的layout()方法。
具体流程如下:
1
、layout方法会设置该View视图位于父视图的坐标轴,即mLeft,mTop,mLeft,mBottom(调用setFrame()函数去实现)。接下来回调onLayout()方法(如果该View是ViewGroup对象,需要实现该方法,对每个子视图进行布局)

2、如果该View是个ViewGroup类型,需要遍历每个子视图chiildView,调用该子视图的layout()方法去设置它的坐标值。

public void layout(int l, int t, int r, int b) {  
       int oldL = mLeft;  
       int oldT = mTop;  
       int oldB = mBottom;  
       int oldR = mRight;  
       boolean changed = setFrame(l, t, r, b);  
       if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {  
           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;  
   }  

函数中参数l、t、r、b是指view的左、上、右、底的位置,这几个参数是父视图传入的,而根视图中参数是由performTraversals()方法传入的。

host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);  

我们关注一下LinearLayout:

@Override  
  protected void onLayout(boolean changed, int l, int t, int r, int b) {  
      if (mOrientation == VERTICAL) {  
          layoutVertical();  
      } else {  
          layoutHorizontal();  
      }  
  }  

void layoutVertical() {  
      final int paddingLeft = mPaddingLeft;  

      int childTop;  
      int childLeft;  

      // Where right end of child should go  
      final int width = mRight - mLeft;  
      int childRight = width - mPaddingRight;  

      // Space available for child  
      int childSpace = width - paddingLeft - mPaddingRight;  

      final int count = getVirtualChildCount();  

      final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;  
      final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;  

      switch (majorGravity) {  
         case Gravity.BOTTOM:  
             // mTotalLength contains the padding already  
             childTop = mPaddingTop + mBottom - mTop - mTotalLength;  
             break;  

             // mTotalLength contains the padding already  
         case Gravity.CENTER_VERTICAL:  
             childTop = mPaddingTop + (mBottom - mTop - mTotalLength) / 2;  
             break;  

         case Gravity.TOP:  
         default:  
             childTop = mPaddingTop;  
             break;  
      }  

      for (int i = 0; i < count; i++) {  
          final View child = getVirtualChildAt(i);  
          if (child == null) {  
              childTop += measureNullChild(i);  
          } else if (child.getVisibility() != GONE) {  
              final int childWidth = child.getMeasuredWidth();  
              final int childHeight = child.getMeasuredHeight();  

              final LinearLayout.LayoutParams lp =  
                      (LinearLayout.LayoutParams) child.getLayoutParams();  

              int gravity = lp.gravity;  
              if (gravity < 0) {  
                  gravity = minorGravity;  
              }  
              final int layoutDirection = getLayoutDirection();  
              final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);  
              switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {  
                  case Gravity.CENTER_HORIZONTAL:  
                      childLeft = paddingLeft + ((childSpace - childWidth) / 2)  
                              + lp.leftMargin - lp.rightMargin;  
                      break;  

                  case Gravity.RIGHT:  
                      childLeft = childRight - childWidth - lp.rightMargin;  
                      break;  

                  case Gravity.LEFT:  
                  default:  
                      childLeft = paddingLeft + lp.leftMargin;  
                      break;  
              }  

              if (hasDividerBeforeChildAt(i)) {  
                  childTop += mDividerHeight;  
              }  

              childTop += lp.topMargin;  
              setChildFrame(child, childLeft, childTop + getLocationOffset(child),  
                      childWidth, childHeight);  
              childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);  

              i += getChildrenSkipCount(child, i);  
          }  
      }  
  }  

layout设置了view的位置,还设置了子视图位置,layoutHorizontal()方法中调用了setChildFrame方法:

layoutHorizontal函数:

private void setChildFrame(View child, int left, int top, int width, int height) {          
    child.layout(left, top, left + width, top + height);  
} 

从上面看出,layout也是一个自上而下的过程,先设置父视图位置,在循环子视图,父视图位置一定程度上决定了子视图位置。

3.Draw()过程

draw过程调用顺序在measure()和layout()之后,同样的,performTraversals()发起的draw过程最终会调用到mView的draw()函数,值得注意的是每次发起绘图时,并不会重新绘制每个View树的视图,而只会重新绘制那些“需要重绘”的视图,View类内部变量包含了一个标志位DRAWN,当该视图需要重绘时,就会为该View添加该标志位。

调用流程 :
mView.draw()开始绘制,draw()方法实现的功能如下:
1 、绘制该View的背景;
2 、为显示渐变框做一些准备操作(见5,大多数情况下,不需要改渐变框);
3、调用onDraw()方法绘制视图本身
(每个View都需要重载该方法,ViewGroup不需要实现该方法);
4、调用dispatchDraw
()方法绘制子视图(如果该View类型不为ViewGroup,即不包含子视图,不需要重载该方法)值得说明的是,ViewGroup类已经为我们重写了dispatchDraw
()的功能实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能;
5、
dispatchDraw()方法内部会遍历每个子视图,调用drawChild()去重新回调每个子视图的draw()方法(注意,这个
地方“需要重绘”的视图才会调用draw()方法)。值得说明的是,ViewGroup类已经为我们重写了dispatchDraw()的功能;
实现,应用程序一般不需要重写该方法,但可以重载父类函数实现具体的功能。
6、绘制滚动条;

于是,整个调用链就这样递归下去了。看一下view类的draw方法。

draw函数:

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) {  
           final Drawable background = mBackground;  
           if (background != null) {  
               final int scrollX = mScrollX;  
               final int scrollY = mScrollY;  

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

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

       // 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);  

           // 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);  
           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);  
           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);  
           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);  
           canvas.drawRect(right - length, top, right, bottom, p);  
       }  

       canvas.restoreToCount(saveCount);  

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

draw方法分成了6个步骤:

/*  
        * 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)  
        */ 

可以看到,第三部, Draw view’s
content步骤调用了onDraw方法,子类中实现onDraw方法;第四步,Draw
children步骤使用的dispatchDraw方法,这个方法在ViewGroup中有实现。
View或ViewGroup的子类不用再重载ViewGroup中该方法,因为它已经有了默认而且标准的view系统流程。dispatchDraw()内部for循环调用drawChild()分别绘制每一个子视图,而drawChild()内部又会调用draw()函数完成子视图的内部绘制工作。

dispatchDraw函数:

/** 
    * {@inheritDoc} 
    */  
   @Override  
   protected void dispatchDraw(Canvas canvas) {  
       final int count = mChildrenCount;  
       final View[] children = mChildren;  
       int flags = mGroupFlags;  

       if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {  
           final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;  

           final boolean buildCache = !isHardwareAccelerated();  
           for (int i = 0; i < count; i++) {  
               final View child = children[i];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {  
                   final LayoutParams params = child.getLayoutParams();  
                   attachLayoutAnimationParameters(child, params, i, count);  
                   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 saveCount = 0;  
       final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;  
       if (clipToPadding) {  
           saveCount = 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 ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {  
           for (int i = 0; i < count; i++) {  
               final View child = children[i];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {  
                   more |= drawChild(canvas, child, drawingTime);  
               }  
           }  
       } else {  
           for (int i = 0; i < count; i++) {  
               final View child = children[getChildDrawingOrder(count, i)];  
               if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {  
                   more |= drawChild(canvas, child, drawingTime);  
               }  
           }  
       }  

       // 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 (debugDraw()) {  
           onDebugDraw(canvas);  
       }  

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

       // 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);  
       }  
   }  

最后说说那些“需要重绘”的视图
请求重绘View树,即draw()过程,假如视图发生大小没有变化就不会调用layout()过程,并且只绘制那些“需要重绘的”
视图,即谁(View的话,只绘制该View
;ViewGroup,则绘制整个ViewGroup)请求invalidate()方法,就绘制该视图。

一般引起invalidate()操作的函数如下:
1、直接调用invalidate()方法,请求重新draw(),但只会绘制调用者本身。
2、setSelection()方法 :请求重新draw(),但只会绘制调用者本身。
3、setVisibility()方法 :
当View可视状态在INVISIBLE转换VISIBLE时,会间接调用invalidate()方法,继而绘制该View。
4 、setEnabled()方法 :
请求重新draw(),但不会重新绘制任何视图包括该调用者本身。**
requestLayout()方法** :会导致调用measure()过程 和 layout()过程
,只是对View树重新布局layout过程包括measure()和layout()过程,不会调用draw()过程,但不会重新绘制
任何视图包括该调用者本身。
一般引起invalidate()操作的函数如下:
1、setVisibility()方法:
当View的可视状态在INVISIBLE/ VISIBLE
转换为GONE状态时,会间接调用requestLayout() 和invalidate方法。
同时,由于整个个View树大小发生了变化,会请求measure()过程以及draw()过程,同样地,只绘制需要“重新绘制”的视图。

** requestFocus()**函数说明:
请求View树的draw()过程,但只绘制“需要重绘”的视图。

上面基本介绍完了View的绘制流程。更多的细节需要在日常学习中总结。

发表评论

电子邮件地址不会被公开。 必填项已用*标注