Android Activity的视图结构-装载过程
目标
1.通过源码得出Android Activity的视图结构
2.了解视图装载过程
handleLaunchActivity
备注:关于Activity的启动过程,我们后面再做分析
Activity的启动都会进去ActivityThread.handleLaunchActivity中
ActivityThread.performLaunchActivity
//创建activity的context实例
ContextImpl appContext = createBaseContextForActivity(r);
//ClassLoader创建当前activity实例
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//获取app实例,上面app的创建中已经存在
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
//回调activity的onCreate方法
mInstrumentation.callActivityOnCreate
performLaunchActivity中
1.创建activity的context实例
2.使用ClassLoader创建当前activity实例
3.makeApplication获取app实例,app的创建中已经存在
4.调用activity.attach方法
5.使用mInstrumentation回调activity的onCreate方法
我们这里重点看activity.attach
Activity.attach
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setCallback(this);
mWindowManager = mWindow.getWindowManager();
1.创建了PhoneWindow实例
2.mWindow.getWindowManager最终通过返回 new WindowManagerImpl(mContext, parentWindow)返回WindowManagerImpl实例
setContentView
在onCreate方法回调之后回到我们自定义的Activity中,这里我们需要调用Activity.setContentView,将xml layout资源设置给Activity
那我们接下来看Activity.setContentView
Activity.setContentView
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
getWindow即为mWindow对象,PhoneWindow实例
initWindowDecorActionBar即为Activity创建ActionBar
顺便可以看Window抽象类的注释,表示仅有一个实现类PhoneWindow
* The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window
PhoneWindow.setContentView
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
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;
}
installDecor
mDecor = generateDecor(-1);
mContentParent = generateLayout(mDecor);
generateDecor相当于new了一个集成自FrameLayout的DecorView对象
new DecorView(context, featureId, this, getAttributes())
DecorView extends FrameLayout
generateLayout
//初始化PhoneWindow的一些flag和成员属性和decor的属性 动画
//mStatusBarColor mNavigationBarColor
mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
decor.setSystemUiVisibility
params.windowAnimations
int layoutResource;
//根据不同的features属性(也就是系统的UI风格)加载不同的layout布局
layoutResource = R.layout.screen_simple;
mDecor.startChanging();
//将layout布局加载到mDecor中
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
//用window去寻找R.id.content的viewgroup
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
//public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
mDecor.setWindowBackground(mBackgroundDrawable);
这里可以出generateLayout主要初始化PhoneWindow的一些flag、动画、成员属性,mStatusBarColor、mNavigationBarColor,动画
设置decor的属性(背景),然后去寻找R.id.content的ViewGroup
这里的findViewById其实是调用Window的findViewById,所以最终是在decorView中寻找R.id.content
@Nullable
public T findViewById(@IdRes int id) {
return getDecorView().findViewById(id);
}
那么他所需要找的id View应该来源于上面onResourcesLoaded的资源,那么我们随便找一个layout看一下,比如R.layout.screen_simple;
主要layout不在SDK的源码包中,需要到framework中查找,当然可以去一些网站搜索文件得到源码,https://www.androidos.net.cn/sourcecode,随便推一个,可得到
可以看到该布局文件包含了ViewStub和FrameLayout,FrameLayout即为需要找到的R.id.content的组件。
然后我们接着看DecorView的onResourcesLoaded方法干了啥,使用inflater.inflate(layoutResource, null)加载layoutResource,
void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
if (mBackdropFrameRenderer != null) {
loadBackgroundDrawablesIfNeeded();
mBackdropFrameRenderer.onResourcesLoaded(
this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
getCurrentColor(mNavigationColorViewState));
}
mDecorCaptionView = createDecorCaptionView(inflater);
final View root = inflater.inflate(layoutResource, null);
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();
}
那么到这里可以有如下结论:
1.DecorView实质是一个FrameLayout;
2.DecorView会根据不同的features加载一个Framework中的布局文件,该布局文件中包含R.id.content的FrameLayout;
3.mContentParent = generateLayout中,mContentParent 就是R.id.content的FrameLayout
到此installDecor已经全部结束,接着下面mLayoutInflater.inflate(layoutResID, mContentParent)
LayoutInflater.inflate
在installDecor之后,就是将我们自己实现的xml布局文件使用LayoutInflater.inflate,通过解析xml中的view,使用反射创建相应的View,然后递归创建出所有的子View,然后将xml转化后的view add到mContentParent中。
LayoutInflater.inflate的具体过程将不再分析。
StatusBar、NavigationBar
以下内容基于Android29
StatusBar、NavigationBar在DecorView定义,DecorView在onDraw方法中会使用BackgroundFallback将StatusBar和NavigationBar画出。
private final ColorViewState mStatusColorViewState =
new ColorViewState(STATUS_BAR_COLOR_VIEW_ATTRIBUTES);
private final ColorViewState mNavigationColorViewState =
new ColorViewState(NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES);
private static class ColorViewState {
View view = null;
int targetVisibility = View.INVISIBLE;
boolean present = false;
boolean visible;
int color;
final ColorViewAttributes attributes;
ColorViewState(ColorViewAttributes attributes) {
this.attributes = attributes;
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
mBackgroundFallback.draw(this, mContentRoot, c, mWindow.mContentParent,
mStatusColorViewState.view, mNavigationColorViewState.view);
}
mNavigationColorViewState.view mStatusColorViewState.view的创建是在DecorView的updateColorViewInt中
if (view == null) {
if (showView) {
state.view = view = new View(mContext);
setColor(view, color, dividerColor, verticalBar, seascape);
view.setTransitionName(state.attributes.transitionName);
view.setId(state.attributes.id);
visibilityChanged = true;
view.setVisibility(INVISIBLE);
state.targetVisibility = VISIBLE;
LayoutParams lp = new LayoutParams(resolvedWidth, resolvedHeight,
resolvedGravity);
if (seascape) {
lp.leftMargin = sideMargin;
} else {
lp.rightMargin = sideMargin;
}
addView(view, lp);
updateColorViewTranslations();
}
}
updateColorViewInt何时调用
1.DecorView实现了WindowCallbacks接口
2.ViewRootImpl持有DecorView的WindowCallbacks实例
3.ViewRootImpl.performTraversals开始绘制时回调onWindowDragResizeStart方法
4.DecorView中的onWindowDragResizeStart调用updateColorViews,绘制StatusBar、NavigationBar
所以StatusBar、NavigationBar是在绘制的时候添加上去的
View的装载过程
视图结构
参考文章:https://www.jianshu.com/p/7a904184afc6