這篇文章距離現(xiàn)在已經(jīng)兩年的時間了。當(dāng)初自己剛畢業(yè)工作不久,才開始接觸Android,有一天中午和同事一起吃飯的時候,一個大牛問我你思考過Activity的setContentView是怎么執(zhí)行的么。當(dāng)初就因?yàn)檫@個問題我接入到了Android源碼。兩年時間過去了現(xiàn)在回過頭來看,感覺自己寫得有很多的不足,本次再補(bǔ)充一下。
前言
這幾天正在進(jìn)行初級自定義組件的學(xué)習(xí),一不小心想到了view到底是怎么加載到屏幕上面的。每一個Activity中都有一個方法setContentView,我們可以加載自己想要的界面布局,展示在手機(jī)屏幕上。但到底內(nèi)部是怎么實(shí)現(xiàn)的呢?(PS:源碼基于Android5.1,cm12.1)
Activity的onContentView
首先查看Activity的onContentView的方法:
//Activity.java
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initActionBar();
}
public void setContentView(View view) {
getWindow().setContentView(view);
initActionBar();
}
public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initActionBar();
}
Activity一共重載了三個setContentView方法,其中第一個setContentView(int layoutResID)方法是我們常用的。
public void setContentView(int layoutResID) {
//getWindow()獲取activity內(nèi)部對象mWindow并調(diào)用它的setContentView方法
getWindow().setContentView(layoutResID);
initActionBar(); //這是初始化actionBar,我們不關(guān)注它
}
public Window getWindow() {
return mWindow;
}
Activity的setContentView方法實(shí)際還是調(diào)用mWindow的setContentView方法,接下看我們試看看mWindow的相關(guān)代碼。
mWindow對象
查看Activity源碼,找到在attach方法中對mWindow做了賦值。
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) {
attachBaseContext(context);
mFragments.attachActivity(this, mContainer, null);
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
/…部分代碼省略…/
}
那么Activity的attach方法是Activity生命周期的第一個方法,它是ActivityThread中performLaunchActivity方法調(diào)用的,這是通過AMS(ActivityManagerService)的startActivity調(diào)用ActivityTrack的startActivityMayWait來調(diào)用的。
attach字面意思就是“使依附;貼上;系上”,也就是點(diǎn)擊activity進(jìn)行啟動的時候之執(zhí)行的。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
/*******部分代碼省略********/
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
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 (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
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);
/*******部分代碼省略********/
}
如述源代碼當(dāng)中就是在啟動Activity的時候執(zhí)行其attach:
- ApplicationThread#scheduleLaunchActivity
- ActivityThread#handleLaunchActivity
- ActivityThread#performLaunchActivity
- Activity#attach
PolicyManager獲取Window對象
public final class PolicyManager {
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";
private static final IPolicy sPolicy;
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);
}
}
// Cannot instantiate this class
private PolicyManager() {}
// The static methods to spawn new policy-specific objects
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
/*******部分代碼省略********/
}
PolicyManager.makeNewWindow方法實(shí)際是通過反射機(jī)制調(diào)用了"com.android.internal.policy.impl.Policy"的makeNewWindow方法。
public class Policy implements IPolicy {
private static final String TAG = "PhonePolicy";
private static final String[] preload_classes = {
"com.android.internal.policy.impl.PhoneLayoutInflater",
"com.android.internal.policy.impl.PhoneWindow",
"com.android.internal.policy.impl.PhoneWindow$1",
"com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback",
"com.android.internal.policy.impl.PhoneWindow$DecorView",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState$SavedState",
};
static {
// For performance reasons, preload some policy specific classes when
// the policy gets loaded.
for (String s : preload_classes) {
try {
Class.forName(s);
} catch (ClassNotFoundException ex) {
Log.e(TAG, "Could not preload class for phone policy: " + s);
}
}
}
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
/*******部分代碼省略********/
}
Policy的makeNewWindow方法實(shí)際是返回一個PhoneWindow對象。
PhoneWindow.setContentView
public class PhoneWindow extends Window implements MenuBuilder.Callback {
/*******部分代碼省略********/
@Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// 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) {
//構(gòu)造DecorView對象并賦值給mDecor,并進(jìn)行mContentParent的初始化
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
view.setLayoutParams(params);
final Scene newScene = new Scene(mContentParent, view);
transitionTo(newScene);
} else {
//將附帶params屬性的view對象添加在mContentParent中
mContentParent.addView(view, params);
}
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
@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 {
//將Resource對于的id等于layoutResID的xml布局文件,add到mContentParent中
mLayoutInflater.inflate(layoutResID, mContentParent);
}
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
/*******部分代碼省略********/
}
setContentView主要做了兩件事:
- 初始化整個界面(即:DecorView)
- 將setContentView的參數(shù)對于的View,add到mContentParent中。
addView
setContentView方法有兩種在界面添加View的方法。
- 調(diào)用mContentParent的add方法,將目標(biāo)View添加進(jìn)去。
- 調(diào)用LayoutInfater.inflate方法將資源xml解析并轉(zhuǎn)化為View,添加到mContentParent中。
installDecor
在看installDecor方法的源代碼的時候,我先讓大家看一個Android手機(jī)界面的布局文件的分析圖。
PhoneWindow.java部分代碼
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
private void installDecor() {
if (mDecor == null) {
//構(gòu)造mDecor對象DecorView
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
}
if (mContentParent == null) {
//構(gòu)造mContentParent
mContentParent = generateLayout(mDecor);
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
if (decorContentParent != null) {
//mDecorContentParent賦值R.id.decor_content_parent
mDecorContentParent = decorContentParent;
mDecorContentParent.setWindowCallback(getCallback());
if (mDecorContentParent.getTitle() == null) {
mDecorContentParent.setWindowTitle(mTitle);
}
/*******部分代碼省略********/
}
mDecorContentParent為mDecor中的R.id.decor_content_parent
installDecor先構(gòu)造mDecor,然后通過mDecor執(zhí)行g(shù)enerateLayout()方法初始化mContentParent。
protected ViewGroup generateLayout(DecorView decor) {
/*******部分代碼省略********/
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);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
/*******部分代碼省略********/
return contentParent;
}
mContentRoot為decor的content,經(jīng)測試(mContentRoot == mDecorContentParent)為true。
generateLayout(DecorView decor)方法構(gòu)造出來的mContentParent為ID_ANDROID_CONTENT,即mDecor中的R.id.content。
從代碼中可以看出顯示獲取當(dāng)前窗口的根ViewGroup(mDecor),然后往這個ViewGroup中添加view。
最終我們要展示在Activity中的View已經(jīng)構(gòu)造好了,那么在Activity的onResume 方法之后,在 ActivityThread#handleResumeActivity 方法中會將該View通過WindowManager添加在Activity所掛在的Window上進(jìn)行展現(xiàn)。
mDecor是什么可以參考博客:DecorView淺析
好了學(xué)習(xí)過程到此結(jié)束~!
下邊介紹在我學(xué)習(xí)過程中膜拜的博客,感覺這些大牛就是點(diǎn)亮我前行的燈塔,哈哈哈。
Android View的加載過程
Android應(yīng)用setContentView與LayoutInflater加載解析機(jī)制源碼分析
android的窗口機(jī)制分析------UI管理系統(tǒng)
文章到這里就全部講述完啦,若有其他需要交流的可以留言哦~!~!