美文网首页嵌牛IT观察
View的工作原理之layout过程

View的工作原理之layout过程

作者: 浩浩_72a0 | 来源:发表于2017-12-14 21:33 被阅读0次

姓名:李昕洲      学号:16030120026

转载自:http://blog.csdn.net/gongxiaoou/article/details/78806188

【嵌牛导读】:大家或多或少了解过View,本文将为你揭晓View的工作原理之layout过程。

【嵌牛鼻子】:View树、layout过程。

【嵌牛提问】:View树从上到下的布局过程如何? getMeasuredWidth和getWidth的本质区别是什么?

【嵌牛正文】:

layout和onLayout方法的作用

layout用来确定View自己的位置,onLayout用来确定各个子View的位置

在View类中只有layout的实现,没有onLayout的实现,因为不同的实现类有不同特殊情况。

如下为View类中的onLayout

view sourceprint?

/**

    *布置子类

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

    }

下面是layout方法,这里我们只关心我们要的代码其他的省略。

@SuppressWarnings({"unchecked"})

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

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {

            onLayout(changed, l, t, r, b);

            ...省略代码...

        }

    }

layout流程大致如下:首先通过setFrame设置View的四个顶点在父View的位置,那么此View的位置就确定了;然后调用onLayout方法确定各个子View的位置。

下面是setFrame方法(看注释部分即可):

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;

          //判断尺寸是否发生了变化

          boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

          // Invalidate our old position

          invalidate(sizeChanged);

          mLeft = left;

          mTop = top;

          mRight = right;

          mBottom = bottom;

          mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

          mPrivateFlags |= PFLAG_HAS_BOUNDS;

          if (sizeChanged) {

              //改变尺寸,但是我们发现它的具体操作也是交给了子类根据具体情况实现

              sizeChange(newWidth, newHeight, oldWidth, oldHeight);

          }

          if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {

              // If we are visible, force the DRAWN bit to on so that

              // this invalidate will go through (at least to our parent).

              // This is because someone may have invalidated this view

              // before this call to setFrame came in, thereby clearing

              // the DRAWN bit.

              mPrivateFlags |= PFLAG_DRAWN;

              invalidate(sizeChanged);

              // parent display list may need to be recreated based on a change in the bounds

              // of any child

              invalidateParentCaches();

          }

          // Reset drawn bit to original value (invalidate turns it off)

          mPrivateFlags |= drawn;

          mBackgroundSizeChanged = true;

          if (mForegroundInfo != null) {

              mForegroundInfo.mBoundsChanged = true;

          }

          notifySubtreeAccessibilityStateChangedIfNeeded();

      }

      return changed;

  }

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

          //判断尺寸是否发生了变化

          boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

          // Invalidate our old position

          invalidate(sizeChanged);

          mLeft = left;

          mTop = top;

          mRight = right;

          mBottom = bottom;

          mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

          mPrivateFlags |= PFLAG_HAS_BOUNDS;

          if (sizeChanged) {

              //改变尺寸,但是我们发现它的具体操作也是交给了子类根据具体情况实现

              sizeChange(newWidth, newHeight, oldWidth, oldHeight);

          }

          if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {

              // If we are visible, force the DRAWN bit to on so that

              // this invalidate will go through (at least to our parent).

              // This is because someone may have invalidated this view

              // before this call to setFrame came in, thereby clearing

              // the DRAWN bit.

              mPrivateFlags |= PFLAG_DRAWN;

              invalidate(sizeChanged);

              // parent display list may need to be recreated based on a change in the bounds

              // of any child

              invalidateParentCaches();

          }

          // Reset drawn bit to original value (invalidate turns it off)

          mPrivateFlags |= drawn;

          mBackgroundSizeChanged = true;

          if (mForegroundInfo != null) {

              mForegroundInfo.mBoundsChanged = true;

          }

          notifySubtreeAccessibilityStateChangedIfNeeded();

      }

      return changed;

  }

下面以LinearLayout为例子来分析onLayout方法。

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

        }

    }

这里我们以mOrientation == VERTICAL为例分析。

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

        final int paddingLeft = mPaddingLeft;

        int childTop;

        int childLeft;

        // 父View的宽度

        final int width = right - left;

        //得到所有子View的最右边界

        int childRight = width - mPaddingRight;

        //所有子View占用的横向空间

        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;

        //根据子View在父View中的Gravity(上,下,左,右,中)来计算子所有View的上边界

        switch (majorGravity) {

          case Gravity.BOTTOM:

              // mTotalLength contains the padding already

              childTop = mPaddingTop + bottom - top - mTotalLength;

              break;

              // mTotalLength contains the padding already

          case Gravity.CENTER_VERTICAL:

              childTop = mPaddingTop + (bottom - top - 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) {

                //获取单个子View的测试宽高

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

                //获取每个子View的左边界

                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;

                }

                //逐个累计各个子View的竖直方向占用空间为布置下一个子View做准备

                if (hasDividerBeforeChildAt(i)) {

                    childTop += mDividerHeight;

                }

                childTop += lp.topMargin;

                //最终让每个子View各自完成自己的layout

                setChildFrame(child, childLeft, childTop + getLocationOffset(child),

                        childWidth, childHeight);

                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

                i += getChildrenSkipCount(child, i);

            }

        }

    }

下面是setChildFrame方法,其实就是让每个子View完成自己的layout。

private void setChildFrame(View child, int left, int top, int width, int height) {       

        child.layout(left, top, left + width, top + height);

}

上面基本就将整个View树的layout展示了一下。

下面我们来解释getMeasuredWidth和getWidth的本质区别(高度方向原理一样)

先看layoutHorizontal—->setChildFrame

void layoutHorizontal(int left, int top, int right, int bottom) {

    ...省略代码...

    final int childWidth = child.getMeasuredWidth();

    final int childHeight = child.getMeasuredHeight();

    setChildFrame(child, childLeft, childTop + getLocationOffset(child),

                            childWidth, childHeight);

    ...省略代码...

}

private void setChildFrame(View child, int left, int top, int width, int height) {       

        child.layout(left, top, left + width, top + height);

}

从中我们发现父View给子View布置的宽高(childWidth, childHeight)就是它的测量宽高getMeasuredWidth(),getMeasuredHeight()。

再看layout和setFrame方法和getWidth和getHeight

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

    ...省略代码...

}

protected boolean setFrame(int left, int top, int right, int bottom) {

    ...省略代码...

    mLeft = left;

    mTop = top;

    mRight = right;

    mBottom = bottom;

    ...省略代码...

}

public final int getWidth() {

        return mRight - mLeft;

}

public final int getHeight() {

        return mBottom - mTop;

}

从上面可以看出getMeasuredWidth和getWidth其实值是一样的,只是获取的时间点不同,measuredWidth(测量宽度)形成于View的measure过程中,而View的width(真实宽度)形成于layout过程中。

补充说明:我们可以撑的没事重写layout如下,这会造成无法正常显示等错误,这只是为了证明可以让测量宽/高度不等于最终宽/高度。

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

    super.layout(l, t, r+10, b+10);

}

而且有的View需要多次measure过程,那么在这个过程中测量宽/高度不等于最终宽/高度,但是最终测量宽/高度等于最终宽/高度public void layout(int l, int t, int r, int b) {

    super.layout(l, t, r+10, b+10);

}

而且有的View需要多次measure过程,那么在这个过程中测量宽/高度不等于最终宽/高度,但是最终测量宽/高度等于最终宽/高度

相关文章

网友评论

    本文标题:View的工作原理之layout过程

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