一、View的绘制流程是哪里开始的?
准备知识:Activity的启动流程
View的绘制入口可以在ActivityThread的handleResumeActivity这个方法看到。
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
// 这方法里面最终会判断去调用onReStart onStart onResume生命周期
r = performResumeActivity(token, clearHide, reason);
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) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
// 我们的View是添加在ViewManager--》WindowManager--》WindowManagerImpl(这个实现类)
// View 的绘制流程是从这里开始的
wm.addView(decor, l);
}
}
}
}
}
- View的绘制流程其实就是从ViewManager.addView(View view, ViewGroup.LayoutParams params)这个方法开始的。
二、ViewManager这个类在哪里创建?
1. ViewManager wm = a.getWindowManager(); 调用的就是Activity的方法
public WindowManager getWindowManager() {
return mWindowManager;
}
// mWindowManager 是在attch方法里面赋的值
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,
Window window, ActivityConfigCallback activityConfigCallback) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
// 在这个方法里面创建的值
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());
}
// 在这里赋的值,最终拿到的是WindowManagerImpl这个类
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
mWindow.setColorMode(info.colorMode);
}
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) {
// ViewManager这个类在这里创建,是系统的一个服务:WindowManager
wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
}
// WindowManagerImpl其实就是new出来的
mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
}
public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
return new WindowManagerImpl(mContext, parentWindow);
}
类的关系:类WindowManagerImpl 实现了 WindowManager 接口,WindowManager接口 继承了ViewManager接口。
三、查看WindowManagerImpl 这个类,addView的代码
public final class WindowManagerImpl implements WindowManager {
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
private final Context mContext;
private final Window mParentWindow;
private IBinder mDefaultToken;
private WindowManagerImpl(Context context, Window parentWindow) {
mContext = context;
mParentWindow = parentWindow;
}
public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
return new WindowManagerImpl(mContext, parentWindow);
}
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
// 其实调的是WindowManagerGlobal.addView方法
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.updateViewLayout(view, params);
}
@Override
public void removeView(View view) {
mGlobal.removeView(view, false);
}
@Override
public void removeViewImmediate(View view) {
mGlobal.removeView(view, true);
}
@Override
public void requestAppKeyboardShortcuts(
final KeyboardShortcutsReceiver receiver, int deviceId) {
IResultReceiver resultReceiver = new IResultReceiver.Stub() {
@Override
public void send(int resultCode, Bundle resultData) throws RemoteException {
List<KeyboardShortcutGroup> result =
resultData.getParcelableArrayList(PARCEL_KEY_SHORTCUTS_ARRAY);
receiver.onKeyboardShortcutsReceived(result);
}
};
try {
WindowManagerGlobal.getWindowManagerService()
.requestAppKeyboardShortcuts(resultReceiver, deviceId);
} catch (RemoteException e) {
}
}
@Override
public Display getDefaultDisplay() {
return mContext.getDisplay();
}
}
四、查看WindowManagerGlobal这个类,addView的代码
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
// ViewRootImpl是实现的ViewParent接口的子类
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
// 创建ViewRootImpl
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 {
// View开始绘制的关键方法
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
}
}
五、查看ViewRootImpl 这个类,setView的代码
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
// 删掉了N行代码
// 关键方法,请求布局
requestLayout();
// 删掉了N行代码
}
}
}
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
// 检查UI线程,看是不是和创建View的线程一致。
checkThread();
mLayoutRequested = true;
// 真正开始的方法
scheduleTraversals();
}
}
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
// 里面通过Handler发送消息执行mTraversalRunnable任务。
// 最终也就是执行mTraversalRunnable这是个Runnable对象的run()方法
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
六、查看TraversalRunnable这个类,run()的代码
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
final class TraversalRunnable implements Runnable {
@Override
public void run() {
// 又去执行ViewRootImpl类的doTraversal()
doTraversal();
}
}
// ViewRootImpl类里面的方法
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
// View的测量、摆放、绘制的关键方法
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
// ViewRootImpl类里面的方法
private void performTraversals() {
// ...省略N行代码
// 测量View
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
// 摆放View
performLayout(lp, mWidth, mHeight);
// 绘制View
performDraw();
// ...省略N行代码
}
七、总结performMeasure、performLayout、performDraw三个方法
一、performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)
--> mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)
--> onMeasure(widthMeasureSpec, heightMeasureSpec);
1. performMeasure方法是指定和测量布局中所有控件的宽高。
2. 对于ViewGrop,先去循环测量子View的宽高,然后根据子View测量宽高来计算和指定自己的宽高。
3. 对于View,它的宽高是由父View和自己的测量模式计算决定的。
二、performLayout(lp, mWidth, mHeight)
-->> host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
-->> onLayout(changed, l, t, r, b);
1. 用于摆放子控件。
2. 对于ViewGrop,循环子View,然后调用子View的 child.layout(l,t,r,b)方法摆放子View。
3. 对于View是空实现。
三、performDraw()
-->> drawSoftware()
-->> mView.draw(canvas);
--> drawBackground(canvas);-->onDraw(canvas);--> dispatchDraw(canvas);--> onDrawForeground(canvas);
1. 用于绘制自己和子View
2. 如果设置了前景和前景,无论是View还是ViewGrop都会调用方法去绘制。
3. 对于ViewGrop,会调用dispatchDraw方法,在方法里面循环调用子View的draw()方法,来绘制子View。
4. 对于View,会去调用onDraw(canvas)去绘制自己。