Android View工作原理详解(一)

在Android开发中,如果你想了解一个View的工作原理或者你想根据需求自定义View ,那么View的Measure,Layout,draw三大流程是你是怎么也绕不开的。在正式介绍View的三大流程之前,我们必须先介绍一些基本概念,这样才能更好的理解View的measure、layout、draw三个过程。
本文涉及到内容


image.png

ViewRoot——三大流程的开始

ViewRoot对应于源码中的ViewRootImpl类,它是连接WIndowManager和DecorView的 纽带,View的三大流程都是通过ViewRootImpl来完成的。ViewRootImp的创建是在WindowManagerGlobal类的addView()方法中,具体源码:

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);
        } else {
            // If there's no parent, then hardware acceleration for this view is
            // set from the application's hardware acceleration setting.
            final Context context = view.getContext();
            if (context != null
                    && (context.getApplicationInfo().flags
                            & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }

        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 (int i = mRoots.size() - 1; i >= 0; --i) {
                                mRoots.get(i).loadSystemProperties();
                            }
                        }
                    }
                };
                SystemProperties.addChangeCallback(mSystemPropertyUpdater);
            }

            int index = findViewLocked(view, false);
            if (index >= 0) {
                if (mDyingViews.contains(view)) {
                    // Don't wait for MSG_DIE to make it's way through root's queue.
                    mRoots.get(index).doDie();
                } else {
                    throw new IllegalStateException("View " + view
                            + " has already been added to the window manager.");
                }
                // The previous removeView() had not completed executing. Now it has.
            }

            // 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.size();
                for (int i = 0; i < count; i++) {
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                        panelParentView = mViews.get(i);
                    }
                }
            }

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

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(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.
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
                throw e;
            }
        }
    }

View的绘制流程是从ViewRoot的performTraversals()方法开始,经过三大流程将View绘制出来,其中measure用来测量View的宽高,layout用来确定View在父布局中的位置,draw负责将View绘制在屏幕上。
针对performTraversals的大致流程如下:

performTraversals流程图

performTraversals依次调用performMeasure,performLayout,performDraw方法完成顶层view的绘制,onMeasure,onLayout,onDraw三个方法中会对调用子View的相关流程,完成所有子View的绘制流程。
Measure过程决定了View的宽高,Measure过程完成以后,可以通过getMeasureWidth和getMeasureHeight获取view的测量宽高,在绝大部分情况下,测量宽高就等于view的最终宽高。layout过程决定了view的四个顶点的坐标和View最终的宽高,完成以后可以通过getWidth/getHeight方法获取view的最终宽高。Draw过程决定了View的显示,只有Draw过程完成以后,View的内容才会呈现在屏幕上。

DecorView——最顶层的View

DecorView是FrameLayout的子类,它被认为是Android视图树的根节点视图。DecorView作为顶级View,一般情况下它内部包含一个竖直方向的LinearLayout。其与Activity,window的关系如下图:

Activity,window,DecorView之间的关系

DecorView的创建是在PhoneWindow的installDecor()方法中,这里摘取installDecor的部分代码:

private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }

DecorView 是通过generateDecor()得到的,以下是generateDecor的源码

protected DecorView generateDecor(int featureId) {
        // System process doesn't have application context and in that case we need to directly use
        // the context we have. Otherwise we want the application context, so we don't cling to the
        // activity.
        Context context;
        if (mUseDecorContext) {
            Context applicationContext = getContext().getApplicationContext();
            if (applicationContext == null) {
                context = getContext();
            } else {
                context = new DecorContext(applicationContext, getContext());
                if (mTheme != -1) {
                    context.setTheme(mTheme);
                }
            }
        } else {
            context = getContext();
        }
        return new DecorView(context, featureId, this, getAttributes());
    }

MeasureSpec

在view的三大流程中,测量的过程是比较复杂的,为了更好地理解view的Measure过程,我们需要先弄清楚MeasureSpec。
MeasureSpec代表一个32位的Int值,高两位代表SpecMode,SpecMode是值测量模式,剩下的30位代表SpecSize,SpecSize是指在某种测量模式下的大小。通过一个Int值避免了过多的内存对象分配,方便操作。
通过源码,我们可以看出MeasureSpec定义了三种SpecMode:

public static class MeasureSpec {
        private static final int MODE_SHIFT = 30;
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        /** @hide */
        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
        @Retention(RetentionPolicy.SOURCE)
        public @interface MeasureSpecMode {}

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

(1)UNSPECIFIEND
父容易不对 View 有任何影响,要多大给多大,这种情况一般用于系统内部。

(2)EXACTLY
父容器已经检测出 View 所需要的精确大小,这个时候 View 的最终大小就是 MeasureSpec 所指定的值,它对应于 LayoutParams 的 match_parent 和具体的数值两种模式。

(3)AT_MOST
父容器指定一个大小即 SpecSize,View 的大小不能大于这个值,具体是什么值要看不同 View 的具体实现,它对应于 LayoutParams 的warp_content。

MeasureSpec类中还提供生成MeasureSpec的方法及获取SpecMode和SpecSize的方法。

  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);
            }
        }
/**
         * Extracts the mode from the supplied measure specification.
         *
         * @param measureSpec the measure specification to extract the mode from
         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
         *         {@link android.view.View.MeasureSpec#AT_MOST} or
         *         {@link android.view.View.MeasureSpec#EXACTLY}
         */
        @MeasureSpecMod
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);
        }

View MeasureSpec 和LayoutParams关系

系统内部是通过MeasureSpec来给View 进行测量工作的,但是我们实际却是只用LayoutParams来设置的.这里我们就是分析2者直接的联系。
其实View在测量的时候,系统会将LayoutParams在父容器的约束下转换成对应的MeasureSpec,然后根据这个MeasureSpec来确定View测量之后的高和宽.也就是说MeasureSpec不是由LayoutParams唯一确定的,而是要和父容器一起来确定的.而且普通的View和页面的顶级View(DecorView)的MeasureSpec的转换过程是有些不同的。
DecorView的MeasureSpec是由窗口的尺寸和DecorView其自身的LayoutParams来共同决定的。普通View的MeasureSpec是由父容器的MeasureSpec和普通View自身的LayoutParams来共同决定的。

对于DecorView来说,在VIewRootImp中measureHierarchy方法中有如下代码,展示了decorView的MeasureSpec创建过程:
childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

其中,baseSize是基于当前DisplayMetrics进行转换,获取的指定资源id对应的尺寸,desiredWindowHeight是屏幕高度。
下面是getRootMeasureSpec方法的实现:

private static int getRootMeasureSpec(int windowSize, int rootDimension) {
      int measureSpec;
      switch (rootDimension) {

      case ViewGroup.LayoutParams.MATCH_PARENT:
          // Window can't resize. Force root view to be windowSize.
          measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
          break;
      case ViewGroup.LayoutParams.WRAP_CONTENT:
          // Window can resize. Set max size for root view.
          measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
          break;
      default:
          // Window wants to be an exact size. Force root view to be that size.
          measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
          break;
      }
      return measureSpec;
  }

通过上面代码,我们可以看出,DecorView的MeasureSpec的产生遵循以下规则:
1.LayoutParams.MATCH_PARENT:
SpecSize=windowSize, SpecMode=MeasureSpec.EXACTLY
2.LayoutParams.WRAP_CONTENT:
SpecSize=windowSize, SpecMode=MeasureSpec.AT_MOST
3.固定大小:
SpecSize=rootDimension, SpecMode=MeasureSpec.EXACTLY

其他View的MeasureSpec创建过程与DecorView类似,与其父容器的MeasureSpec和其自身的LayoutParams有关,具体关系表格:


View的MeasureSpec创建规则.png

了解了view三大流程的开始——ViewRootImp和最顶层viewDecorView,我们对view的流程的有了大致的了解。下一篇将详细介绍view的三大流程。理解了MeasureSpec和MeasureSpec与自身LayoutParams关系之后,我们接下来理解View的Measure过程就好理解了。

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