关于view的绘制流程,大家都知道会有onMeasure,onLayout,onDraw。想必也很好奇,为什么view为什么会存在这些绘制周期,到底分发控制的源头在什么地方呢?它又是何方神圣?
1,追溯源头在何地?
(1)特殊activity生命周期onCreate(), onResume()。
先理一理思路,要找到视图分发的源头的话,我们首先要知道我们的视图如何跟activity建立联系。其次,经历了什么过程视图才能真正展现起来?
下面说下这两个方法为什么特殊?我们一般在onCreate中去setContentView将我们主视图给传递给Activity,由此activity就显示其主视图。而onResume是一个视图展示到前台与用户交互的重要关节点,onResume之后才会去正常操作。
(2) 源码剖析setContentView做了什么?
Activity :
public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initActionBar();
}
这时候出现window概念,且视图交给window去维护了。那我们可以这样理解,window窗口辅助activity实际管理视图交互,这样activity就能把主要心思放在自己关注的方面。
Window:
public abstract class Window {
public abstract void setContentView(View view, ViewGroup.LayoutParams params);
}
这是个抽象类,隐藏了具体实现细节,那得找到其真正的实现类了。
Activity:
mWindow = PolicyManager.makeNewWindow(this);
PolicyMananger:
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";
static {
// Pull in the actual implementation of the policy at run-time
try {
Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
sPolicy = (IPolicy)policyClass.newInstance();
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);
} catch (InstantiationException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
}
}
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
Policy:
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
经过重重阻碍找到了真正的Window实现类 PhoneWindow。
该进入正题了:PhoneWindow.setContentView;
PhoneWindow:
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mContentParent.addView(view, params);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);....
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
generateLayout(DecorView decor) {
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
这下我们就知道了实际我们有PhoneWindow窗口管理,而View的层级分别为 DecorView-ContentParent-ContentView
ContentParent会根据我们设置的相关主题等属性找到对应的承载容器。
我们追踪到根视图,及管理窗口PhoneWindow,但是还没有到顶层分发入口。那我们就只能再看看实际视图展现前做了什么?
(3) activity resume做了什么?
涉及到resume调用时机要了解到activtyThread处理activity启动过程了(具体暂不赘述)。
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
boolean reallyResume) {
ActivityClientRecord r = performResumeActivity(token, clearHide);
...
if (r != null) {
final Activity a = r.activity;
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);
}}
}
可以发现,在resume的时候,我们实际的之前创建的decorview才会被加入到窗口管理器中。那我们视图肯定跟窗口管理器有关系了。
现在问题来了WindowManager又是何方神圣?
Activity:(windowMananger设置入口)
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
Window:
public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
boolean hardwareAccelerated) {
mAppToken = appToken;
mAppName = appName;
mHardwareAccelerated = hardwareAccelerated
|| SystemProperties.getBoolean(PROPERTY_HARDWARE_UI, false);
if (wm == null) {
wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
}
mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
}
WindowManangerImpl
public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
return new WindowManagerImpl(mDisplay, parentWindow);
}
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
public void addView(View view, ViewGroup.LayoutParams params) {
mGlobal.addView(view, params, mDisplay, mParentWindow);
}
我们知道WindowMananger实际实现是WindowManagerImpl,而其内部实际实现类为WindowManagerGlobal.
再看看WindowManagerGlobal:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
ViewRootImpl root;
View panelParentView = null;
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
if (mViews == null) {
index = 1;
mViews = new View[1];
mRoots = new ViewRootImpl[1];
mParams = new WindowManager.LayoutParams[1];
} else {
index = mViews.length + 1;
Object[] old = mViews;
mViews = new View[index];
System.arraycopy(old, 0, mViews, 0, index-1);
old = mRoots;
mRoots = new ViewRootImpl[index];
System.arraycopy(old, 0, mRoots, 0, index-1);
old = mParams;
mParams = new WindowManager.LayoutParams[index];
System.arraycopy(old, 0, mParams, 0, index-1);
}
index--;
mViews[index] = view;
mRoots[index] = root;
mParams[index] = 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.
synchronized (mLock) {
final int index = findViewLocked(view, false);
if (index >= 0) {
removeViewLocked(index, true);
}
}
throw e;
}
越发的逼近真相了,我们发现有个ViewRootImpl,字面意思就是“根视图”,没错它就是此次的主角。
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
...
requestLayout();
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mInputChannel);
view.assignParent(this);
}
好啦,最终viewrootimpl调用requestlayout去实现刷新绘制(我们view中也有requestlayout接口是否很熟悉,最终都会调用到这个入口),同时当前窗口与windowmanagerservice建立联系,统筹管理。
assignParent方法后面再说下用途。
我们来写下关系:
Window(PhoneWindow): 包含DecorView(根视图) - contentParent(contentview实际父容器,由主题决定不同父容器) - contentview(activity所传递)
WindowManager(WindowManagerImpl 窗口管理控制) - WindowManagerGlobal (实际全局控制) - ViewRootImpl
(实际视图分发根入口,窗口加入WindowManangerService管理 )
2,viewrootimpl绘制分发
通常我们都会刷新视图,实际刷新基本都依赖requestlayout和invalidate。以requestlayout为例。
View中:
public void requestLayout() {
mPrivateFlags |= PFLAG_FORCE_LAYOUT;
mPrivateFlags |= PFLAG_INVALIDATED;
if (mParent != null && !mParent.isLayoutRequested()) {
mParent.requestLayout();
}
}
我们发现会逐级调用父视图,我们一步步跟,发现DecorView中并没有reqeustLayout重载,这就奇怪了,难道跟丢了?
换个思路:mParent在什么地方产生?
产生一:ViewGroup.addViewInner();
private void addViewInner(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
...
if (preventRequestLayout) {
child.assignParent(this);
} else {
child.mParent = this;
}
}
产生二 view.assignParent:
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");
}
}
带着这两个产生入口去看,我们看看上面viewrootimpl.setView中 有这么一行
view.assignParent(this)
;
好了,就这样我们requestlayout原来最终都会由viewRootImpl负责处理。
越来越接近真相了:
viewRootImpl:
@Override
public void requestLayout() {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
private void performTraversals() {
...
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
...
performLayout();
...
performDraw();
...
}
requestlayout做两件事:(1)校验当前线程是否为主线程 (2)执行Traversals实现视图measure, layout, 和 draw
这下我们就都知道,视图绘制流程分发的根路径了,为什么ui必须要在主线程中调用。