Android View 显示原理分析
当启动一个Activity的时候,Activity执行了onCreate() 、onStart()、 onResume()3个方法后,用户就能看见界面了,相应的XML布局文件中的View是如何显示到屏幕上的?有一个重要的方法是setContentView(R.layout.main_layout),我们一起来看一下setContentView()的执行过程。
一.setContentView()执行流程
跟随调用关系,结合关键类来分析一下执行流程:
1.Activity
当start一个包含界面的activity时,会首先调用setContentView(resourceID),代码如下:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_main_view);
}
跟随调用逻辑,看一下setContentView的实现:
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public Window getWindow() {
return mWindow;
}
private Window mWindow;
mWindow = new PhoneWindow(this, window, activityConfigCallback);
根据Activity的启动过程,mWindow是在attach()时创建的,是PhoneWindow实例,此处是调用到了PhoneWindow里面的setContentView(layoutResID)方法:
2.PhoneWindow
public void setContentView(int layoutResID) {
if (mContentParent == null) {
//初始化DecorView
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
//解析传进来的xml布局,将其加载到mContentParent上
//mContentParent是在installDecor()中创建的,后续会看到
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
首先看一下installDecor()方法:
// This is the top-level view of the window, containing the window decor.
// PhoneWindow的顶层View
private DecorView mDecor;
// This is the view in which the window contents are placed. It is either
// mDecor itself, or a child of mDecor where the contents go.
// 最终内容防置即显示的view
ViewGroup mContentParent;
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
//创建DecorView
mDecor = generateDecor(-1);
......
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
//上个方法中的mContentParent在此创建
mContentParent = generateLayout(mDecor);
}
.......
}
我们可以看到,在installDecor()内部主要执行了两个方法:
一个是generateDecor()来创建DecorView;
一个是generateLayout(mDecorView)来将resId对应的xml文件加载到DecorView上。
//创建DecorView
protected DecorView generateDecor(int featureId) {
......
return new DecorView(context, featureId, this, getAttributes());
}
generateDecor()内部就是创建了一个DecorView对象返回。
//1.将R.layout.screen_simple布局文件通过addView加载到DecorView上
//2.从R.layout.screen_simple布局文件获取到R.id.content控件,返回contentParent给mContentParent
protected ViewGroup generateLayout(DecorView decor) {
......
// Inflate the window decor.
int layoutResource; //是一个布局文件id
int features = getLocalFeatures();
// 根据不同的主题将对应的布局文件id赋值给layoutResource
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
setCloseOnSwipeEnabled(true);
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
......
}
......
else {
layoutResource = R.layout.screen_simple;
}
mDecor.startChanging();
//通过LayoutInflater加载解析layoutResource = R.layout.screen_simple(最常用)布局文件
//该方法执行会在后续的DecorView.java里面介绍
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
//从R.layout.screen_simple里面获取R.id.content控件,获取到contentParent
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
.......
return contentParent;
}
在generateLayout()内部主要做了三件事:
一.找到对应的layoutResource,如果没有特别配置,则返回默认的R.layout.screen_simple;
二.将layoutResource作为参数传入执行DecorView的onResourceLoaded()方法;
三.找到ID_ANDROID_CONTENT对应的view,然后作为contentParent返回;
看一下screen_simple.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<!-- ActionBar -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundInsidePadding="false"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
从布局文件看,DecorView加载上的是一个LinearLayout,返回的contentParent(即activity展示界面)是一个FrameLayout。
3.DecorView
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
......
//通过Inflater解析XML布局文件,得到一个View对象
//root就是DecorView中添加的layoutResource,即R.layout.screen_simple.xml
final View root = inflater.inflate(layoutResource, null);
//通过addView把布局文件添加到DecorView中
if (mDecorCaptionView != null) {
if (mDecorCaptionView.getParent() == null) {
addView(mDecorCaptionView,
new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
mDecorCaptionView.addView(root,
new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
} else {
// Put it below the color views.
addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
mContentRoot = (ViewGroup) root;
initializeElevation();
}
}
前面说到的,执行generateLayout(DecorView decor)主要做了以下两个工作:
1.创建对应layoutResource = R.layout.screen_simple的布局,然后将布局加载到DecorView中;
2.从加载的布局文件中找到R.id.content控件,返回contentParent,供activity显示界面;
再回到PhoneWindow.java中的setContentView()方法:
public void setContentView(int layoutResID) {
if (mContentParent == null) {
//初始化DecorView
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
//----------分析--------------------
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
分析:执行mLayoutInflater.inflate(layoutResID, mContentParent)解析布局并加载,将setContentView()传进来的xml布局解析加载到mContentParent上,mContentParent是R.layout.screen_simple.xml中的FrameLayout,然后将activity中setContentView()传进来的xml布局解析加载到mContentParent上。
4.简单总结
a、在PhoneWindow中创建顶层的DecorView;
b、在DecorView中会根据主题的不同加载一个不同的布局,默认加载R.layout.screen_simple.xml;
c、从加载到DecorView中的布局中找到contentParent(即FrameLayout);
d、把Activity中的布局解析并添加到contentParent中;
引用大佬画的图,比较清晰,setContentView()涉及到的布局结构及布局文件如下:
setContentView布局.png
5.执行流程图
setContentView().png二.View的显示
当执行到handleResumeActivity时,Activity的onResume()方法被调用,然后WindowManager会将DecorView设置给ViewRootImpl,这样DecorView就被加载到Window中了,此时界面还没有显示出来,还需要经过View的measure,layout和draw方法,才能完成View的工作流程。
View的绘制是由ViewRootImpl来负责的,每一个DecorView都有一个与之关联的ViewRootImpl,这种关联关系是由WindowManager维护的,将DecorView和ViewRootImpl关联(通过ViewRootImpl的setView方法)之后,ViewRootImpl的requestLayout会被调用以完成初步布局,通过scheduleTraversals方法向主线程发送消息请求遍历,最终调用ViewRootImpl的performTraversals方法,这个方法会执行View的measure,layout 和draw流程。
1.png
源码调用流程如下:
1.ActivityThread
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
......
//回调到activity的onResume()方法
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
final Activity a = r.activity;
......
if (r.window == null && !a.mFinished && willBeVisible) {
//获取到PhoneWindow
r.window = r.activity.getWindow();
//获取DecorView
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 (r.mPreserveWindow) {
a.mWindowAdded = true;
r.mPreserveWindow = false;
// Normally the ViewRoot sets up callbacks with the Activity
// in addView->ViewRootImpl#setView. If we are instead reusing
// the decor view we have to notify the view root that the
// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
//通过WindowManager.addView加载DecorView
wm.addView(decor, l);
} else {
// The activity will get a callback for this {@link LayoutParams} change
// earlier. However, at that time the decor will not be set (this is set
// in this method), so no action will be taken. This call ensures the
// callback occurs with the decor set.
a.onWindowAttributesChanged(l);
}
}
......
}
}
wm是一个接口ViewManager对象,而wm是通过Activity的getWindowManager()获取的,会调用到WindowManagerImpl.addView(),最终会调用到WindowManagerGlobal.addView():
2.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);
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;
}
}
在addView()内部会创建ViewRootImpl对象,然后执行ViewRootImpl的setView()方法:
3.ViewRootImpl
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
.......
// Schedule the first layout -before- adding to the window
// manager, to make sure we do the relayout before receiving
// any other events from the system.
requestLayout();
......
}
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
//check是否为主线程
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
private void performTraversals() {
.......
.......
.......
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
......
// Ask host how big it wants to be
//Measure
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
......
//layout
performLayout(lp, mWidth, mHeight);
......
//Draw
performDraw();
}
在setView()执行后,经过一步一步的调用,最终执行到performTraversals(),在该方法内部执行view的测量、放置、绘制工作。
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
通过performMeasure()从根节点向下遍历View树,完成所有ViewGroup和View的测量工作,计算出所有ViewGroup和View显示出来需要的高度和宽度;
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
......
try {
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
......
}
......
}
通过performLayout()从根节点向下遍历View树,完成所有ViewGroup和View的布局计算工作,根据测量出来的宽高及自身属性,计算出所有ViewGroup和View显示在屏幕上的区域;
private void performDraw() {
......
try {
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
.......
.......
.......
}
private void draw(boolean fullRedrawNeeded) {
.......
.......
.......
}
通过performDraw()从根节点向下遍历View树,完成所有ViewGroup和View的绘制工作,根据布局过程计算出的显示区域,将所有View的当前需显示的内容画到屏幕上;
4.简单总结
image.png以上简单描述了一下Activity执行setContentView()后的执行过程,View显示绘制还涉及到WMS等复杂的相关处理逻辑,可以参考以下文章:
Android WMS窗口管理
Android WMS窗口管理(二)
三.其他
a.是否只能在主线程更新UI?
通过上面的分析可以看到,View的显示是在onResume()之后才进行绘制的,所以在onCreate()内部可以通过new Thread()来更新UI;
当绘制完成后,就只能通过主线程更新了,为什么?
1.为了解决多线程并发的问题!防止各个线程同时更新UI,就会出现界面错乱的问题。详情可参考Android Handler消息机制详解
2.硬性判断checkThread(),在更新UI前都会判断当前是否为主线程,否则的话直接抛异常;
b.在onResume()中能否获取到view的宽高?
通过上面的分析可以看到,View的显示是在onResume()之后才进行绘制的,从而执行onMeasure(),只有绘制完成后,才能获取到view的宽高;
c.如何在onCreate()确保View获取到宽高后进行UI逻辑处理?
可以通过View.post(Runnable),在Runnable内的run()方法内进行UI的逻辑处理,详情可参考Android View.post()原理分析