从requestLayout()初探View的绘制原理
在自定义View时,涉及到View的大小变化时,通常会涉及到一个函数requestLayout()
,字面意思大家都知道是要求重新执行View的绘制中的layout,但是requestLayout()
是如何做到让View重新绘制的呢?只是简单调用本身的layout(...)
方法么?
public void requestLayout() {
...
if (mParent != null && !mParent.isLayoutRequested()) {
mParent.requestLayout();
}
....
}
可以看到,View
类的requestLayout()
是调用ViewParent
的requestLayout()
方法,但是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()
时,而是Activity
的onCreate
方法,因为ActivityThread
先调用了performLaunchActivity
方法创建了activity并执行onCreate
方法,而onCreate
方法中的setContentView
会调用PhoneWindow
的setContentView
方法,这里最先执行了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
,其在Activity
的attach
方法中被初始化
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()
方法,然后又调用View
的assignParent(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();
}
}
...
}
其中performMeasure
、performLayout
、performDraw
最后基本都是去执行了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