美文网首页
Android View 布局流程(Layout)源码解析

Android View 布局流程(Layout)源码解析

作者: linda_zhou | 来源:发表于2017-08-18 10:36 被阅读0次

    前言

    Android View 测量流程(Measure)源码解析中,我们分析了View的measure过程,确定了View的测量宽/高。当View确定了自身的大小后,View是怎么确定自身在布局中的位置的呢?本篇就来分析一下View的layout过程,文中源码基于 Android API 21。

    View布局流程

    由setContentView探究Activity界面加载流程及Activity、Window和DecorView的关系中,我们提到View三大工作流程是从ViewRootImpl#performTraversals开始的,其中performMeasureperformLayoutperformDraw方法分别对应了View的测量、布局、绘制。因此我们从performLayout开始分析View布局流程。

        private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
                int desiredWindowHeight) {
            mLayoutRequested = false;
            mScrollMayChange = true;
            mInLayout = true;
    
            final View host = mView;
    
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
            try {
                host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
                //省略...
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
            mInLayout = false;
        }
    

    方法中的mView其实就是DecorView,那么host也就代表了DecorView,DecorView其实是个FrameLayout,ViewGroup并没有重写layout方法,所以我们来看下View#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 = 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) {
                        //如果注册了OnLayoutChangeListener,这里将执行回调。
                        listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                    }
                }
                //省略...
            }
            //省略...
        }
    

    layout方法是用来确定自身位置的,其内部调用了setOpticalFramesetFrameonLayout方法,setOpticalFrame内部又会调用setFrame。所以我们先来看setFrame方法,如下:

        protected boolean setFrame(int left, int top, int right, int bottom) {
            boolean changed = false;
    
            if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
                //判断View的位置是否发生改变
                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的尺寸是否发生改变
                boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
    
                // Invalidate our old position
                invalidate(sizeChanged);
                
                //对mLeft、mTop、mRight 、mBottom初始化,View自身的位置也就确定了。
                mLeft = left;
                mTop = top;
                mRight = right;
                mBottom = bottom;
                mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
    
                mPrivateFlags |= PFLAG_HAS_BOUNDS;
                
                //如果View尺寸发生改变,将执行View#sizeChange方法,在sizeChange方法内部会调用View#onSizeChanged方法。
                if (sizeChanged) {
                    sizeChange(newWidth, newHeight, oldWidth, oldHeight);
                }
                //省略...
            }
            return changed;
        }
    

    setFrame方法中对mLeftmTopmRightmBottom进行初始化,mLeftmTop分别对应View左上角的横坐标和纵坐标,mRightmBottom分别对应了View右下角的横坐标和纵坐标,View的四个顶点的坐标确定了,View自身的位置也就确定了。

    再回到layout方法,在通过setFrame方法确定了自身位置后,接下来会调用onLayout方法,这个方法其实用来确定子View的位置的。不过View和ViewGroup都没有真正实现onLayout,因为onLayout和onMeasure类似,其过程都与具体的布局有关。

    下面我们以FrameLayout为例来分析onLayout过程,FrameLayout#onLayout

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            layoutChildren(left, top, right, bottom, false /* no force left gravity */);
        }
    

    其内部调用了layoutChildren方法

    void layoutChildren(int left, int top, int right, int bottom,
                                      boolean forceLeftGravity) {
            final int count = getChildCount();//获取子View的数量
            
            //parentLeft、parentTop分别代表子View所占区域左上角的横坐标和纵坐标
            //parentRight、parentBottom分别代表子View所占区域右下角的横坐标和纵坐标
            final int parentLeft = getPaddingLeftWithForeground();
            final int parentRight = right - left - getPaddingRightWithForeground();
    
            final int parentTop = getPaddingTopWithForeground();
            final int parentBottom = bottom - top - getPaddingBottomWithForeground();
    
            mForegroundBoundsChanged = true;
            
            //遍历子View
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                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;
                  
                    //获取子View 设置的Gravity,如果子View没有设置Gravity,则用默认的Gravity:DEFAULT_CHILD_GRAVITY。
                    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;
    
                    //水平方向上,通过设置的Gravity,来确定childLeft,即每个子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;
                    }
                    
                    //竖直方向上,通过设置的Gravity,来确定childTop,即每个子View左上角的纵坐标
                    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;
                    }
                    
                    //调用子View的layout 方法
                    child.layout(childLeft, childTop, childLeft + width, childTop + height);
                }
            }
        }
    

    在该方法内部遍历所有子View过程中,通过子View设置的Gravity,获去其childLeftchildTop即子View的左上角的横坐标和纵坐标,最后执行子View的layout方法,来确定子View的位置。

    总结

    View通过layout方法确定自身的位置后,通过在onLayout方法中调用子View的layout方法来确定子View的位置。如此反复,便完成了整个View树的layout过程。

    至此,View的布局流程就分析完了,希望能对您有所帮助,若文中有错误或表述不当的地方还望指出,互相交流,共同成长!

    相关阅读:
    由setContentView探究Activity界面加载流程及Activity、Window和DecorView的关系
    Android View 测量流程(Measure)源码解析
    Android View 绘制流程(Draw)源码解析

    相关文章

      网友评论

          本文标题:Android View 布局流程(Layout)源码解析

          本文链接:https://www.haomeiwen.com/subject/gxnirxtx.html