View工作原理

View工作原理

首先先来说明一下要掌握的知识

  • View绘制工作整体流程
  • Measure
  • Layout
  • Draw

View绘制整体流程

View的绘制是从ViewRoot的performTraversals方法开始的。

ViewRoot的作用

对应与ViewRootImpl类,View的三大流程都是通过ViewRoot来完成的。在Activity被创建后,会将DecorView添加到Window中,同时创建ViewRoot的对应类的对象和DecorView关联。

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

继续回到View绘制的入口,ViewRoot的performTraversals方法。

大致流程如图


image

首先可以看出三大流程的调用顺序是measure-->layout-->draw

以measure为例,稍微说明。详细说明看下面的measure过程。
performTraversals方法调用ViewGroup的performMeasure方法,performMeasure调用measure方法,measure方法又调用onMeasure方法,在onMeasure方法中,会遍历调用子View的measure方法,这样就完成了整个View树的遍历。

上面还提到了DecorView,为什么在这里要提到DecorView呢?因为DecorView是顶级容器,View层的事件都必须通过DecorView传给相应的View。这也是View工作流程的一部分。

作为顶级容器,DecorView是一个FrameLayout,其中一般包含一个垂直的LinearLayout(包含TitleView和ContentView)。其中contentView的id是R.android.content

Measure

MeasureSpec

MeasureSpec是参与view的measure流程中的一个重要成员。

 public static class MeasureSpec {
      private static final int MODE_SHIFT = 30;
      private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
        /**
       * Measure specification mode: The parent has not imposed any constraint
       * on the child. It can be whatever size it wants.
       */
      public static final int UNSPECIFIED = 0 << MODE_SHIFT;

      /**
       * Measure specification mode: The parent has determined an exact size
       * for the child. The child is going to be given those bounds regardless
       * of how big it wants to be.
       */
      public static final int EXACTLY     = 1 << MODE_SHIFT;

      /**
       * Measure specification mode: The child can be as large as it wants up
       * to the specified size.
       */
      public static final int AT_MOST     = 2 << MODE_SHIFT;
      
      
      public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                        @MeasureSpecMode int mode) {
          if (sUseBrokenMakeMeasureSpec) {
              return size + mode;
          } else {
              return (size & ~MODE_MASK) | (mode & MODE_MASK);
          }
      }
      
      @MeasureSpecMode
      public static int getMode(int measureSpec) {
          //noinspection ResourceType
          return (measureSpec & MODE_MASK);
      }

      /**
       * Extracts the size from the supplied measure specification.
       *
       * @param measureSpec the measure specification to extract the size from
       * @return the size in pixels defined in the supplied measure specification
       */
      public static int getSize(int measureSpec) {
          return (measureSpec & ~MODE_MASK);
      }
      //省略代码..........
  }

源码写的很清楚,MeasureSpec主要管理一个32为的int类型的值,高两位代表SpecMode,低30位代表SpecSize。

SpecMode有三种:

  • UNSPECIFIED
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;

    高2位为00,表示父容器对view没有约束,要多大给多大。

  • EXACTLY
    public static final int EXACTLY = 1 << MODE_SHIFT;

    高2位为01,表示父容器已经知道了view的大小,这时候SpecSize就是view的最终大小。对应LayoutParams中的match_parent和具体数值大小。

  • AT_MOST
    public static final int AT_MOST = 2 << MODE_SHIFT;

    高2位是10,表示父容器会提供一个可用大小(SpecSize),view的大小不能超过这个SpecSize;,具体大小是多少要看不同view的具体实现。对应LayoutParams中的wrap_content。

上面提到了MeasureSpec和LayoutParams的一些关系,下面来解析一下LayoutParams如何转换成对应的MeasureSpec。

MeasureSpec和Layoutparams的对应关系

我们给view设置大小通常是给View设置LayoutParams,在view的测量过程中,系统会将LayoutParams在父容器的约束下转换成MeasureSpec;这里DecorView和普通View的测量还有点不一样。DecorView的Measure是由窗口尺寸和自身的LayoutParams决定的;而普通的View是由父容器的MeasureSpec和自身的LayoutParams决定的。Measure确定后,就可以在onMeasure方法中获取view的测量宽高

DecorView的MeasureSpec

在ViewRootImpl里有这样一个方法measureHierarchy,里面有DecorView的MeasureSpec的创建过程。

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

desiredWindowWidth,desiredWindowHeight就是屏幕的宽高。

再看看getRootMeasureSpec是怎么实现的。

        private static 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的SpecMode原来是从LayoutParam中得来的。

普通的View的measure

之前说过View的measure过程;他是从ViewGroup中传递过来的。

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

首先获取到了Childview的MarginLayoutparams,然后通过getChildMeasureSpec来获得子view的MeasureSpec。然后将子View的MeasureSpec的数据传给子View,接下来就是ziView的measure过程。getChildMeasureSpec这个方法有好多参数。可以看到,子view的MeasureSpec的创建与父容器的MeasureSpec还有自身的Layoutparams有很大关系。下面就看一下getChildMeasureSpec如何得到子view的MeasureSpec。

/**
     * Does the hard part of measureChildren: figuring out the MeasureSpec to
     * pass to a particular child. This method figures out the right MeasureSpec
     * for one dimension (height or width) of one child view.
     *
     * The goal is to combine information from our MeasureSpec with the
     * LayoutParams of the child to get the best possible results. For example,
     * if the this view knows its size (because its MeasureSpec has a mode of
     * EXACTLY), and the child has indicated in its LayoutParams that it wants
     * to be the same size as the parent, the parent should ask the child to
     * layout given an exact size.
     *
     * @param spec The requirements for this view
     * @param padding The padding of this view for the current dimension and
     *        margins, if applicable
     * @param childDimension How big the child wants to be in the current
     *        dimension
     * @return a MeasureSpec integer for the child
     */
    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;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } 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;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

同样的来分析这个函数,和DecorView的MeasureSpec创建差不多。首先,通过父容器的MeasureSpec获取父容器的SpecMode,和SpecSize;
获取到SpecSize后会计算出留给子View的大小空间(非负)。根据父容器的SpecMode来计算子View的MeasureSpec。有三种情况

  • 父容器的SpecMode是MeasureSpec.EXACTLY:
    • 1.子view的LayoutParams对应的是一个具体数值,那这个具体数值就赋值给resultSize(子View的SpecSize);resultmode(子View的SpecMode)因为是具体数值,所以就是MeasureSpec.EXACTLY;
    • 2.子view的LayoutParams对应的是LayoutParams.MATCH_PARENT,那就把父容器留给子View的大小空间size赋值给resultSize(子View的SpecSize);resultmode(子View的SpecMode)因为是具体数值size,所以就是MeasureSpec.EXACTLY;
    • 3.子view的LayoutParams对应的是LayoutParams.WRAP_CONTENT,那就把父容器留给子View的大小空间size赋值给resultSize(子View的SpecSize);resultmode(子View的SpecMode)因为LayoutParams.WRAP_CONTENT,所以就是MeasureSpec.EXACTLY;
  • 父容器的SpecMode是MeasureSpec.AT_MOST
    • 1.......
    • 2.......
    • 3.......
  • 父容器的SpecMode是MeasureSpec.UNSPECIEFIED
    • 1.......
    • 2.......
    • 3.......

到这里已经介绍了MeasureSpec。之后可以具体看看是如何通过MeasureSpec来得到View的测量大小。

measure过程

待续。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容