源码分析:View的工作流程

简介

View的工作流程主要是指measure、layout、draw这三大流程。其中measure确定View的测量宽高,layout确定View的最终宽高和四个顶点的位置,draw则将View绘制到屏幕上。

View的工作流程入口

在开始三大流程之前,还有一些其他工作,例如将DecorView加载到Window中。并且三大流程的开始是通过ViewRootImpl来调用的。

DecorView被加载到Window中

当在Activity的onCreate中调用setContentView方法时,将会创建DecorView。当DecorView创建完毕后,要加载到Window中。这一过程需要从Activity的创建过程说起,先看ActivityThread的handleLaunchActivity方法:

ActivityThread#handleLaunchActivity

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //...

        Activity a = performLaunchActivity(r, customIntent);   //该方法会调用onCreate   

        if (a != null) {
            //...
            
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason); 

        } else {
            //...
        }
    }

(1)处的performLaunchActivity将会调用onCreate方法,从而完成DecorView的创建。现在看handleResumeActivity方法:

ActivityThread#handleResumeActivity

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        ActivityClientRecord r = mActivities.get(token);
        //...
        
        r = performResumeActivity(token, clearHide, reason);    //调用onResume

        if (r != null) {
            final Activity a = r.activity;

            //...
            
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();       //得到DecorView
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();

                //...
        
                if (a.mVisibleFromClient && !a.mWindowAdded) {
                    //由于WindowManager的实现类是WindowManagerImpl,所以实际
                    //调用的是WindowManagerImpl的addView方法
                    wm.addView(decor, l);   
                }

            } 
            
            //...
        }
    }

继续看WindowManagerImpl的addView方法:

WindowManagerImpl#addView

    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        //mGlobal是一个WindowManagerGlobal对象
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

继续看WindowManagerGlobal的addView方法:

WindowManagerGlobal#addView

    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        //...

        ViewRootImpl root;

        synchronized (mLock) {
            //...

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

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);

            try {
                root.setView(view, wparams, panelParentView);
            } 
            //...
        }
    }

通过ViewRootImpl的setView方法,ViewRootImpl和DecorView建立联系,并将DecorView加载到Window中。

小结

在Activity创建过程中,在onCreate中通过setContentView方法可以完成DecorView的创建。之后在调用完onResume后,需要将DecorView加载到Window中。这个过程需要ViewRootImpl的帮助,ViewRootImpl是连接WindowManager和DecorView的桥梁。通过ViewRootImpl的setView方法,ViewRootImpl和DecorView建立联系,并将DecorView加载到Window中。

开始View的工作流程

通过ViewRootImpl的performTraversals方法开始View的工作流程

ViewRootImpl#performTraversals

    private void performTraversals() {

        //...
    
                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                        updatedConfiguration) {

                    //调用DecorView的measure方法
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

                    boolean measureAgain = false;

                    if (lp.horizontalWeight > 0.0f) {
                        measureAgain = true;
                    }
                    if (lp.verticalWeight > 0.0f) {
                        measureAgain = true;
                    }

                    //需要重新measure
                    if (measureAgain) {
                        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                    }

                }                    

        //...
    
        if (didLayout) {
            //调用DecorView的layout方法
            performLayout(lp, mWidth, mHeight);

            //...
        }

        //...

        if (!cancelDraw && !newSurface) {
            //...

            //调用View的draw方法
            performDraw();
        } 
        
        //...
    }

可以看到,在performTraversals方法中,ViewRootImpl先后执行了performMeasure、performLayout和performDraw方法,这三个方法分别调用了顶级View的measure、layout和draw方法。

measure过程

measure过程要分情况来看,如果是一个View,那么通过measure方法就完成了测量。如果是一个ViewGroup,那么除了完成自己的测量外,还要遍历所有子元素并调用其measure方法。

View的measure过程

View#measure

View的measure过程由其measure方法开始:

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

        if (forceLayout || needsLayout) {
            //...
            
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                onMeasure(widthMeasureSpec, heightMeasureSpec);
            }

            //...
        }

        //...
    }

可以看到,measure是一个final方法,意味着子类不能重写该方法。measure方法继续调用onMeasure方法:

View#onMeasure

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

其中,setMeasuredDimension方法设置View宽高的测量值,getDefaultSize方法得到宽高的测量值。来看下getDefaultSize方法:

View#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的SpecMode来确定,AT_MOST和EXACTLY模式返回的值都是MeasureSpec的SpecSize。所以一般来说SpecSize就是测量后的大小。

至于UNSPECIFIED模式,一般是用于系统内部的测量过程。这种情况下宽高的测量值是由getSuggestedMinimumWidth和getSuggestedMinimumHeigh方法决定的。两个方法同理,这里只分析下getSuggestedMinimumWidth方法:

View#getSuggestedMinimumWidth

    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

其中mMinWidth对应于android:minWidth属性指定的值,如果没有指定该属性,mMinWidth默认为0。mBackground.getMinimumWidth()返回的是背景Drawable的原始宽度。

所以该方法的逻辑是:如果没有设置背景,则返回minWidth属性对应的值。否则返回minWidth属性对应的值和背景Drawable的原始宽度中的较大值。

小结

View的measure过程从measure方法开始,调用onMeasure方法确定测量宽高。测量宽高的确定取决于宽高的MeasureSpec。如果SpecMode为AT_MOST或EXACTIY,测量大小为SpecSize。如果SpecMode为UNSPECIFIED,需要判断有无背景,如果没有设置背景,测量大小为minWidth属性对应的值;否则测量大小为minWidth属性对应的值和背景Drawable的原始宽度中的较大值。但是UNSPECIFIED模式一般是用于系统内部的测量过程,所以我们平常使用的View的测量大小就是SpecSize

注意

直接继承View的自定义控件需要重写onMeasure()方法,并设置wrap_content时的自身大小,否则在布局中使用wrap_content就相当于使用match_parent。

这是因为在当View使用wrap_content是,他的specMode是AT_MOST,而且View的specSize是parentSize,既父容器的当前剩余空间大小,这与match_parent一致。

如何解决这个问题?需要重写onMeasure方法,代码如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, mHeight);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mWidth, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, mHeight);
    }
}

我们只需要给View指定一个宽高(mWidth, mHeight),并在wrap_content时设置此宽高即可。至于这个宽高如何确定,需要根据View的类型灵活确定。对于非wrap_content的情形,我们仍使用系统的测量值。

ViewGroup的measure过程

ViewGroup#measureChildren

ViewGroup是一个抽象类,它并没有重写onMeasure方法,而是交由各个实现类来重写。但是它提供了一个measureChildren方法来测量每个子View,实现如下:

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

该方法遍历各子View,并调用measureChild方法来测量单个子View

ViewGroup#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);
    }

该方法先得到子View宽高的MeasureSpec,然后调用子View的measure方法进行测量

小结

ViewGrop本身是一个抽象类,其内部并没有重写View的onMeasure方法,但提供了一个measureChildren()方法来对每一个子元素进行measure。之所以没有重写onMeasure方法,是因为ViewGroup的子类具有各种不同的布局特性,所以测量方式不同,这需要子类自己重写onMeasure方法来定义测量规则。

注意

View的measure完成之后,通过getMeasuredWidth、getMeasuredHeight方法就可以获得View的测量宽高。需要注意的是,在某些极端情况下,系统可能要多次measure才能获得最终的测量宽高,这时在onMeasure方法获得的测量宽高可能是不准确的。一个比较好的习惯是在onLayout方法中去获取View的测量宽高

layout过程

View#layout

由于ViewGroup也是调用父类View的layout方法,所有先从View的layout方法看起:

    public void layout(int l, int t, int r, int b) {
        //...

        //初始化四个顶点的值
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        //如果视图的大小和位置发生变化,调用onLayout
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);

            //...
        }

        //...
    }

该方法的步骤是:先初始化四个顶点的值,确定View在其父容器中的位置。如果发现View的大小和位置发生了变化,会继续调用onLayout方法确定子元素的位置。

View和ViewGroup都没有实现onLayout,而是交由具体的ViewGroup来实现。下面看下LinearLayout的onLayout方法:

LinearLayout#onLayout

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

只看竖向排列的情况,调用layoutVertical方法

LinearLayout#layoutVertical

    void layoutVertical(int left, int top, int right, int bottom) {
        //...

        final int count = getVirtualChildCount();

        //...

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

                //...
                
                //确定子元素的位置
                setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                        childWidth, childHeight);
                        
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

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

该方法遍历子元素,并通过setChildFrame方法确定子元素的位置

LinearLayout#setChildFrame

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

可以看出,setChildFrame方法又是调用子元素的layout方法来确定子元素的位置

小结

View只需确定自己四个顶点的位置即可确定自己的位置,而ViewGroup除了要确定自己的位置,如果发现自己的大小和位置发生了变化,还要调用onLayout重新确定子元素的位置。而在确定子元素位置的时候,又会调用其layout方法,直到所有的View都确定位置。

注意

在View的默认实现中,View的测量宽高和最终宽高是相等的,只不过测量宽高形成于View的measure过程,而最终宽高形成于View的layout过程。因此,一般情况下,我们可以认为View的测量宽高等于最终宽高,但是在某些特殊情况会导致两者不一样:

第一种情况如下:

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r + 100, b + 100);
    }

上面重写了View的layout方法,将导致会View的最终宽高比测量宽高大100px,虽然这样做会导致View显示不正常并且也没有实际意义。

另一种情况是在某些情况,View需要多次measure才能确定自己的测量宽高,那么可能前几次得出的测量宽高和最终宽高不一致,但最终的测量宽高还是和最终宽高相同。

draw过程

View#draw

由于ViewGroup并没有重写draw方法,所以只需看View的draw方法即可:

   public void draw(Canvas canvas) {
        //...

        //绘制背景
        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        //...
        if (!verticalEdges && !horizontalEdges) {
          
            //绘制自己
            if (!dirtyOpaque) onDraw(canvas);   //View的onDraw方法是一个空方法,需要子类自己实现

            //绘制子元素
            dispatchDraw(canvas);   //在View中是一个空方法,ViewGroup重写了该方法

            //绘制装饰(foreground, scrollbars)
            onDrawForeground(canvas);

            //...
        }

        //...
    }

可以看出,View的绘制过程步骤如下:

  1. 绘制背景:调用背景Drawable的draw方法
  2. 绘制自己:调用onDraw方法,这是一个空方法,需要子类自己实现
  3. 绘制子元素:调用dispatchDraw方法,该方法在View中是一个空方法,ViewGroup重写了该方法
  4. 绘制装饰:调用onDrawForeground方法,绘制foreground, scrollbars等

注意

View有一个特殊的方法setWillNotDraw:

    /**
     * If this view doesn't do any drawing on its own, set this flag to
     * allow further optimizations. By default, this flag is not set on
     * View, but could be set on some View subclasses such as ViewGroup.
     *
     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
     * you should clear this flag.
     *
     * @param willNotDraw whether or not this View draw on its own
     */
    public void setWillNotDraw(boolean willNotDraw) {
        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
    }

从注释可以看出,如果一个View不需要绘制任何内容,那么设置这个标志位为true后,系统会进行相应的优化。默认情况下,View没有启用这个标志位,但是ViewGroup会默认启用这个优化标志位

这个标志位的意义是:当我们自定义的控件继承与ViewGroup并且自身不具备绘制功能(没有重写onDraw)时,就可以开启这个标志位从而便于系统进行后续的优化。相反,当我们需要重写ViewGroup的onDraw方法来绘制内容时,就需要显示地关闭这个标志位

参考

  • 《Android 开发艺术探索》
  • 《Android 进阶之光》
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值