从requestLayout()初探View的绘制原理

在自定义View时,涉及到View的大小变化时,通常会涉及到一个函数requestLayout(),字面意思大家都知道是要求重新执行View的绘制中的layout,但是requestLayout()是如何做到让View重新绘制的呢?只是简单调用本身的layout(...)方法么?

    public void requestLayout() {
        ...
        if (mParent != null && !mParent.isLayoutRequested()) {
            mParent.requestLayout();
        }
        ....
    }

可以看到,View类的requestLayout()是调用ViewParentrequestLayout()方法,但是ViewParent类只是一个接口没有实现,所以我们去找mParent的引用。

我们逐级打印出mParent,会发现最后指向了PhoneWindow$DecorView,也就是我们常说的根View。但是再看下去,发现DecorView其实是FrameLayout的子类,也就是说又指回了View,这下似乎陷入了循环……

mParent也只有在assignParent方法中实现了赋值,但View类本身并没有调用这个方法

void assignParent(ViewParent parent) {
        if (mParent == null) {
            mParent = parent;
        } else if (parent == null) {
            mParent = null;
        } else {
            throw new RuntimeException("view " + this + " being added, but"
                    + " it already has a parent");
        }
    }

那么我们只能从DecorView生成的地方来考虑了,众所周知DecorView作为Activity的根View,那么肯定和Activity生成的地方有关。我们从Activity的创建开始找,最后在ActivityThread类中的handleResumeActivity()方法中,找到对Activity中DecorView的赋值

 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume) {
        ...
        if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (a.mVisibleFromClient) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                }

            // If the window has already been added, but during resume
            // we started another activity, then don't yet make the
            // window visible.
            }
        ...
        }

getDecorView()Window类下的一个抽象方法,而Android中实现了Window的类只有PhoneWindow,于是我们去PhoneWindow中找

这里说明一点,mDecor的创建时间并不是调用getDecorView()时,而是ActivityonCreate方法,因为ActivityThread先调用了performLaunchActivity方法创建了activity并执行onCreate方法,而onCreate方法中的setContentView会调用PhoneWindowsetContentView方法,这里最先执行了installDecor()

@Override
    public final View getDecorView() {
        if (mDecor == null) {
            installDecor();
        }
        return mDecor;
    }
    
   private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        
  protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
  }

好像还是没有线索……但是我们发现在handleResumeActivity方法中DecorView的实例最后被一个ViewManager的子类WindowManager通过addView()添加进去了,会不会跟这个WindowManager有关系呢?

//handleResumeActivity中指向的方法,在Activity.java中
public WindowManager getWindowManager() {
        return mWindowManager;
    }

指向了Activity中的一个变量mWindowManager,其在Activityattach方法中被初始化

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
            ...
            mWindowManager = mWindow.getWindowManager();
            ...
           }

调用到Window类中的方法

/**
     * Return the window manager allowing this Window to display its own
     * windows.
     *
     * @return WindowManager The ViewManager.
     */
    public WindowManager getWindowManager() {
        return mWindowManager;
    }

再去找mWindowManager赋值的地方

 public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }

终于发现了一个不一样的类WindowManagerImpl,这应该就是实现了WindowManager接口的类,看下它的addView()方法

@Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

又扔给了一个mGlobal变量,这个变量属于WindowManagerGlobal类,可以看下这个类的介绍

**
 * Provides low-level communication with the system window manager for
 * operations that are not associated with any particular context.
 *
 * This class is only used internally to implement global functions where
 * the caller already knows the display and relevant compatibility information
 * for the operation.  For most purposes, you should use {@link WindowManager} instead
 * since it is bound to a context.

呃……英文不好自行找词典,大概意思就是提供了一个全局变量来实现底层系统与表现层的沟通,再来看他的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);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
}

可以看到,这里最关键的操作就是初始化了一个ViewRootImpl类的对象,调用它的setView方法注入之前的View。

那么ViewRootImpl类是什么?它的setView方法又做了什么呢?

我们先来看一下ViewRootImlp类的Javadoc

* The top of a view hierarchy, implementing the needed protocol between View
 * and the WindowManager.  This is for the most part an internal implementation
 * detail of {@link WindowManagerGlobal}.
 public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks
        
//View阶层的顶级,实现了View和WindowManager之间需要的协议,这是WindowManagerGlobal

来研究一下它的setView方法

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if(mView ==null){
                 //省略了部分无关代码
                 mView = view;
                requestLayout();
                ...
                view.assignParent(this); 
            }
        }
}

可以看到,setView方法基本只有在第一次调用时才会生效,它先调用了自己的requestLayout()方法,然后又调用ViewassignParent(ViewParent v)方法把自己注入View中

这下就可以确定View最上层的mParent变量,最终指向的是ViewParentImpl类的实例引用

那让我们再来看看ViewParentImpl中如何实现requestLayout()方法的

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread(); //这里是Android中为什么不能用子线程修改ui的关键
            mLayoutRequested = true; //修改标记为true
            scheduleTraversals();
        }
    }

众所周知,Android中是不能用子线程来更新ui的,原因就是在于ViewRootImpl类中的requestLayout方法在执行时,会首先检查当前线程是否是ViewRootImpl实例创建的线程。而唯一的ViewRootImpl对象是在主线程中被系统创建的。所以子线程中更新ui,就会导致checkThread()方法验证失败而抛出异常

除了checkThread()以外,还执行了scheduleTraversals()方法

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

这里执行了Choreographer类的实例的postCallback方法,方法最后将这个Runnable放入Message中发出到MessageQueue中并执行,我们来看这个Runnable做了什么

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

再看看doTraversal()

void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

其中最关键的是执行了performTraversals()方法,这也是View绘制中最关键的一个方法

private void performTraversals() {
     //省略了部分无关代码
     final View host = mView;
     ...
     host.dispatchAttachedToWindow(mAttachInfo, 0);//注入AttachInfo
     ...
     boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
     if (layoutRequested) {
            mLayoutRequested = false;   //清除标记
     }
     ...
     if (!mStopped || mReportNextDraw) {
            ...
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
            int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ...
     }
     ...
     final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
     if (didLayout) {
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
     }
     ...
     boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() ||
                viewVisibility != View.VISIBLE;
        if (!cancelDraw && !newSurface) {
            if (!skipDraw || mReportNextDraw) {
                ...
                performDraw();
            }
        }
     ...
}

其中performMeasureperformLayoutperformDraw最后基本都是去执行了View的measure、layout、draw方法,这也是View绘制三大步骤调用的时间点。

这里我还特地标注一下host.dispatchAttachedToWindow(mAttachInfo, 0)方法,这个方法给View中注入了mAttachInfo的引用,而mAttachInfo的初始化是在ViewRootImpl的构造函数里

public ViewRootImpl(Context context, Display display) {
    ...
    mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
    ...
}

AttachInfo这个类基本就是提供各种底层信息的,借此,Window和View的联系就建立起来了。

最后上一张图来整理下整个调用链

requestLayout

最后欢迎关注我的GithubBlog

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

推荐阅读更多精彩内容