本文源码基于6.0分析。
首先看一下Activity中的setContentView。
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
我们可以看到实际上调用的是getWindow().setContentView(layoutResID),我们知道getWindow()获得的Window对象就是PhoneWindow对象,所以实际上调用的是PhoneWindow中的setContentView(layoutResID)。
PhoneWindow.java
@Override
public void setContentView(int layoutResID) {
//如果mContentParent为null,说明窗口还没有加载内容,则初始化DecorView。
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
//FEATURE_CONTENT_TRANSITIONS标志位,这个是标记当前内容加载有没有使用过度动画,也就是转场动画。
//否则mContentParent不为null,说明已经加载过了,并且没有使用转场动画,那么remove所以view。
mContentParent.removeAllViews();
}
//如果使用转场动画,则调用transitionTo方法
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
//否则将我们的资源文件通过LayoutInflater对象转换为View树,并且添加至mContentParent视图中。
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
接下来我们详细分析以下setContentView方法中调用的方法。
先看一下installDecor()方法。
private void installDecor() {
if (mDecor == null) {
//如果mDecor为null,调用generateDecor()创建
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
}
//mContentParent为 null说明DecorView并未加载到mContentParent中。
if (mContentParent == null) {
//调用generateLayout方法给mContentParent赋值
mContentParent = generateLayout(mDecor);
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
//设置TitleView(TextView),Backdroud等资源,设置有无转场动画以及转场动画的种类
......
}
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
protected ViewGroup generateLayout(DecorView decor) {
TypedArray a = getWindowStyle();
......
//设置style为Window_windowNoTitle或者Window_windowActionBar
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
} else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
// Don't allow an action bar if there is no title.
requestFeature(FEATURE_ACTION_BAR);
}
//省略一些style资源的判断
......
//添加布局到DecorView,前面我们通过generateDecor() 创建DecorView,现在DecorView里面还是null的,下面通过设置的Feature来创建相应的布局。
//举个例子,如果我在setContentView之前调用了requestWindowFeature(Window.FEATURE_NO_TITLE),这里则会通过getLocalFeatures来获取你设置的feature,进而加载对应的布局,
//此时是加载没有标题栏的主题,这也就是为什么我们在代码中设置Theme或者requesetFeature()的时候必须在setContentView之前的原因.
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_title_icons;
}
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
layoutResource = R.layout.screen_progress;
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogCustomTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_custom_title;
}
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = a.getResourceId(
R.styleable.Window_windowActionBarFullscreenDecorLayout,
R.layout.screen_action_bar);
} else {
layoutResource = R.layout.screen_title;
}
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = R.layout.screen_simple_overlay_action_mode;
} else {
layoutResource = R.layout.screen_simple;
}
mDecor.startChanging();
//将相应的布局解析成View并添加到decorView中。
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
mContentRoot = (ViewGroup) in;
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
......
mDecor.finishChanging();
//generateLayout()的返回是contentParent,而它的获取则是ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
//DecorView是顶级View,它可以标示整个屏幕,其中包含状态栏,导航栏,内容区等等。这里的mContentParent指的是屏幕显示的内容区,而我们设置的activity_main.xml布局则是mContentParent里面的一个子元素。
return 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">
<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>
我们再次回到PhoneWindow类的setContentVeiw()方法中,通过调用installDecor()方法,我们已经创建了DecorView,并获取到了mContentParent,接着就是将我们setContentView的内容添加到mContentParent中,也就是mLayoutInflater.inflate(layoutResID, mContentParent);
@Override
public void setContentView(int layoutResID) {
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();
}
}
我们先看一下最后几句代码
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
这个CallBack是Window内部的一个接口,Window中实现了setCallback和getCallback方法。setCallback()方法是在Activity中被调用的。
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) {
mWindow = new PhoneWindow(this);
}
而Activity本身也实现了Window.Callback接口,我们看一下Activity中实现的onContentChanged()方法。
public void onContentChanged() {
}
该方法是一个空方法,而当Activity的布局改动时,即setContentView()或者addContentView()方法执行完毕时就会调用该方法。我们日常开发时可以利用起来。
接下来我们分析一下LayoutInflater.inflat()方法,看是如何将我们自己的布局加载上去的。
到目前为止,通过setContentView方法,创建了DecorView和加载了我们自己的布局,但是View还是不可见的,因为我们只是加载了布局,并没有对View进行任何的测量、布局、绘制工作。
在View进行测量流程之前,还要进行一个步骤,那就是把DecorView添加至window中。
要说把DecorView添加到Window中,那我们就要从Activity的启动说起了,Activity启动的过程中必经的一步—ActivityThread类中的的handleLaunchActivity()方法。
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
......
} else {
......
}
}
我们来看一下performLaunchActivity(r, customIntent)。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
}
......
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
......
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
......
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
......
}
r.paused = true;
mActivities.put(r.token, r);
}
return activity;
}
调用了Instrumentation类的newActivity方法。Instrumentation类是一个全权负责Activity生命周期的类。
public Activity newActivity(Class<?> clazz, Context context,
IBinder token, Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
Object lastNonConfigurationInstance) throws InstantiationException,
IllegalAccessException {
Activity activity = (Activity)clazz.newInstance();
ActivityThread aThread = null;
activity.attach(context, aThread, this, token, 0, application, intent,
info, title, parent, id,
(Activity.NonConfigurationInstances)lastNonConfigurationInstance,
new Configuration(), null, null);
return activity;
}
通过反射创建了一个新的Activity实例,在该方法中调用了Activity类中的attach()方法,回到performLaunchActivity方法中,接下来会调用Instrumentation类的callActivityOnCreate方法。
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
调用了Activity中的performCreate方法。
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
调用了onCreate方法,我们知道onCreate方法是Activity的第一个生命周期方法,在这里我们调用了setContentView(),整个performLaunchActivity()函数就会返回一个已经执行完onCreat()和setContetnView()的activity对象,之前我们说setContentView()执行完之后,View此时还是不可见的,要等DecorView添加至window中,然后触发ViewRootImpl#performTraversals方法开始View的绘制,测量等工作后才会可见。
回到ActivityThread中handleLaunchActivity方法继续看,在执行完performLaunchActivity方法后会执行handleResumeActivity方法。
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);
}
} else if (!willBeVisible) {
if (localLOGV) Slog.v(
TAG, "Launch " + r + " mStartedActivity set");
r.hideForNow = true;
}
cleanUpPendingRemoveWindows(r);
if (!r.activity.mFinished && willBeVisible
&& r.activity.mDecor != null && !r.hideForNow) {
......
WindowManager.LayoutParams l = r.window.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
!= forwardBit) {
l.softInputMode = (l.softInputMode
& (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
| forwardBit;
if (r.activity.mVisibleFromClient) {
ViewManager wm = a.getWindowManager();
View decor = r.window.getDecorView();
wm.updateViewLayout(decor, l);
}
}
r.activity.mVisibleFromServer = true;
mNumVisibleActivities++;
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
}
......
} else {
try {
ActivityManagerNative.getDefault()
.finishActivity(token, Activity.RESULT_CANCELED, null, false);
} catch (RemoteException ex) {
}
}
}
首先执行了performResumeActivity()方法
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
ActivityClientRecord r = mActivities.get(token);
if (r != null && !r.activity.mFinished) {
if (clearHide) {
r.hideForNow = false;
r.activity.mStartedActivity = false;
}
try {
r.activity.onStateNotSaved();
r.activity.mFragments.noteStateNotSaved();
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults);
r.pendingResults = null;
}
r.activity.performResume();
......
} catch (Exception e) {
......
}
}
return r;
}
可看到执行了r.activity.performResume();即Activity中的performResume()方法。
final void performResume() {
......
mInstrumentation.callActivityOnResume(this);
......
onPostResume();
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPostResume()");
}
}
调用了Instrumentation类中的callActivityOnResume()方法.
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
activity.onResume();
......
}
可以看到最终调用了Activity的生命周期方法onResume()。
继续看handleResumeActivity()方法中,performResumeActivity()方法执行完毕后,也就是执行到onResume()方法,此时内容仍然是不可见的,并且还没有执行View的测量、摆放、绘制等操作,因此此时获取View的宽高仍然是0。
handleResumeActivity()方法中。
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
r.activity.getWindow()获得当前Activity的PhoneWindow对象.
View decor = r.window.getDecorView();获得当前phoneWindow内部类DecorView对象.
decor.setVisibility(View.INVISIBLE);刚获得这个DecorView的时候先设置为不可见.
ViewManager wm = a.getWindowManager();创建一个ViewManager对象.
public WindowManager getWindowManager() {
return mWindowManager;
}
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中看一下getWindowManager()的实现。
public WindowManager getWindowManager() {
return mWindowManager;
}
Window类中mWindowManager唯一赋值的地方在setWindowManager方法中。
public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
boolean hardwareAccelerated) {
......
mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
}
调用了WindowManagerImpl中的createLocalWindowManager()方法
public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
return new WindowManagerImpl(mDisplay, parentWindow);
}
可以看到,最终实际上是new了一个WindowManagerImpl对象。
也就是说ViewManager wm = a.getWindowManager();返回的wm是一个WindowManagerImpl类的实例。
继续回到handleResumeActivity方法中。
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);
}
获取Window的LayoutParams属性,将mWindowAdded属性置为true,然后将DecorView添加到wm中,即添加到Window中,此时才是真正将View添加到Window中。
看一下addView方法的实现。
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mDisplay, mParentWindow);
}
可以看到实际上调用了WindowManagerGlobal的addView方法。
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
......
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
final Context context = view.getContext();
if (context != null
&& (context.getApplicationInfo().flags
& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
}
ViewRootImpl root;
View panelParentView = null;
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) {
synchronized (mLock) {
final int index = findViewLocked(view, false);
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;
......
mAdded = true;
int res; /* = WindowManagerImpl.ADD_OKAY; */
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
mInputChannel = new InputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
} catch (RemoteException e) {
mAdded = false;
......
} finally {
if (restore) {
attrs.restore();
}
}
......
}
}
}
传进来的view就是DecorView,首先将mAdded置为true,表明已经成功添加了DecorView,然后调用requestLayout()方法重绘界面。
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
首先调用了checkThread()方法去检查是否在当前线程,这也是为什么我们在子线程中操作View会报异常的原因。接下来调用scheduleTraversals()方法。
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
调用到了mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null),我们看一下mTraversalRunnable这个Runnable对象。
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
继续看doTraversal()方法的实现。
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
里面有一个很重要的方法,performTraversals()它就是我们View真正开始测量、摆放、绘制的入口了。该方法中会依次调用performMeasure、performLayout、performDraw()操作,具体的View绘制流程我们单独拿一篇文章做讲解,这里不做深究。
好我们继续回到handleResumeActivity方法中,刚才是分析的WindowManagerImpl的addView方法,最终会执行到performTraversals()来执行View的绘制。
我们知道此时DecorView已经被添加到了Window中了,但是在添加之前DecorView被设置成不可见了,decor.setVisibility(View.INVISIBLE);
因此此时还是不可见状态,我们继续看handleResumeActivity方法,最后我们可以看到这样一段代码:
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
进入到Activity中看一下makeVisible()方法的实现。
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
我们看到最终调用mDecor.setVisibility(View.VISIBLE)来将DecorView设置成可见,界面也就显示出来了。
从Activity的生命周期的角度来看,也就是onResume()执行完之后,DecorView才开始attach给WindowManager从而显示出来。
总结一下:
Activity在onCreate之前调用attach方法,在attach方法中会创建window对象。window对象创建时并没有创建Decor对象。用户在Activity中调用setContentView,然后调用window的setContentView,这时会检查DecorView是否存在,如果不存在则创建DecorView对象,然后把用户自己的View 添加到DecorView中。
至此,我们就分析完了setContentView方法的流程。
下一篇将分析View的绘制流程,将从performTraversals()方法开始分析。
网友评论