View的如何被添加到屏幕窗口上的
通常我們的Activity中都會有這樣設(shè)置布局的代碼
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
而你有沒有思考過代碼中的activity_main布局是如何被添加到屏幕窗口上的呢高氮?
讓我們先來查看setContentView
的源碼
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback, WindowControllerCallback,
AutofillManager.AutofillClient {
private Window mWindow;
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public Window getWindow() {
return mWindow;
}
...
}
Window
是一個抽象類赎线,setContentView
是類中的一個抽象方法迷捧,那我們再來看看惰拱,在這個抽象類的唯一實現(xiàn)類PhoneWindow.java
中公条,setContentView
方法是如何實現(xiàn)的贝攒。
注:PhoneWindow
在AS中查看不了锌杀,需要下載源碼或者在源碼查看網(wǎng)站查看,位置在 /frameworks/base/core/java/com/android/internal/policy/PhoneWindow.java
入口:PhoneWindow.class中的 setContentView方法
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor(); //@1
} 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); //@2
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
在這個方法中有兩個重點
-
mContentParent
為空時逝钥,調(diào)用installDecor()
初始化父容器 -
mLayoutInflater.inflate(layoutResID, mContentParent);
解析傳入的layoutResID
1. 先來看PhoneWindow.class中的 installDecor()方法
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-1); //@1.1
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor); //@1.2
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
...
}
}
這個方法中的mDecor
變量就是最上層的View容器了屑那,判斷是否為空,如果為空晌缘,通過generateDecor(-1)
新建一個
1.1 來看PhoneWindow.java中的generateDecor(-1)方法
protected DecorView generateDecor(int featureId) {
Context context;
if (mUseDecorContext) {
Context applicationContext = getContext().getApplicationContext();
if (applicationContext == null) {
context = getContext();
} else {
context = new DecorContext(applicationContext, getContext());
if (mTheme != -1) {
context.setTheme(mTheme);
}
}
} else {
context = getContext();
}
return new DecorView(context, featureId, this, getAttributes());
}
通過該方法最后一行可見齐莲,返回的是一個DecorView
對象,而DecorView
是一個繼承自FrameLayout
的容器對象磷箕。
注:AS同樣查看不到DecorView.java,源碼位置 /frameworks/base/core/java/com/android/internal/policy/DecorView.java
1.2 再來看PhoneWindow.java中的generateLayout(DecorView decor)方法
protected ViewGroup generateLayout(DecorView decor) {
...
// Inflate the window decor.
int layoutResource;
int features = getLocalFeatures();
// System.out.println("Features: 0x" + Integer.toHexString(features));
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) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_title_icons;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
// System.out.println("Title Icons!");
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
// Special case for a window with only a progress bar (and title).
// XXX Need to have a no-title version of embedded windows.
layoutResource = R.layout.screen_progress;
// System.out.println("Progress!");
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
// Special case for a window with a custom title.
// If the window is floating, we need a dialog layout
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogCustomTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_custom_title;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
// If no other features and not embedded, only need a title.
// If the window is floating, we need a dialog layout
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;
}
// System.out.println("Title!");
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = R.layout.screen_simple_overlay_action_mode;
} else {
// Embedded, so no decoration is needed.
layoutResource = R.layout.screen_simple;
// System.out.println("Simple!");
}
mDecor.startChanging();
/**
* 方法重點U竽选T兰稀!
**/
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
ProgressBar progress = getCircularProgressBar(false);
if (progress != null) {
progress.setIndeterminate(true);
}
}
...
return contentParent;
}
這個方法實際上很長呜叫,其中很多內(nèi)容是獲取到主題后空繁,根據(jù)主題來設(shè)置Window
特性,例如
if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
requestFeature(FEATURE_ACTION_BAR_OVERLAY);
}
我們主要關(guān)注layoutResource
的初始化操作朱庆,根據(jù)features等條件的不同盛泡,layoutResource
會被賦上不同的值。例如:R.layout.screen_simple娱颊,R.layout.screen_swipe_dismiss傲诵,R.layout.screen_title_icons 等等凯砍。
然后調(diào)用mDecor
對象的方法:
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
追蹤到DecorView
的onResourcesLoaded
方法中
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();
}
可以看到,就是將傳入的layoutResource
通過addView
加到DecorView
對象上拴竹。
再然后回到PhoneWindow
的generateLayout
方法悟衩,看到onResourcesLoaded
之后執(zhí)行了
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
查到mDecor
上的容器【系統(tǒng)ID為 com.android.internal.R.id.content】,并返回contentParent栓拜。
2. 再來看PhoneWindow.class中的 mLayoutInflater.inflate(layoutResID, mContentParent);
實際上座泳,mContentParent
就是在installDecor()
方法中由generateLayout(mDecor)
賦值的提供給用戶填充的容器,無論系統(tǒng)做出什么判斷幕与,將layoutResource賦值成什么布局挑势,它總要包含一個固定的容器ID
,而這個id為@android:id/content的容器就會暴露給用戶啦鸣,用戶setContentView(View view)
的布局也就有了父容器潮饱。
追蹤到LayoutInflater.java
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
// Context對象
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
// 父視圖
View result = root;
try {
// Look for the root node.
int type;
// 找到root元素
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
// 解析merge標簽
if (TAG_MERGE.equals(name)) {
// 如果是merge標簽調(diào)用新方法,將merge標簽內(nèi)的元素全部加載到父視圖中
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 通過xml的tag來解析根視圖
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// 不是merge標簽赏陵,直接解析布局中的視圖
ViewGroup.LayoutParams params = null;
if (root != null) {
// 生成布局參數(shù)
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context.
// 解析temp視圖下的所有view
rInflateChildren(parser, temp, attrs, true);
// 如果root不為空并且attachToRoot為true饼齿,將temp加入到父視圖中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root為空 或者 attachToRoot為false,返回的結(jié)果就是temp
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
throw ie;
} catch (Exception e) {
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
return result;
}
}
最終調(diào)用public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
方法蝙搔,其中第一個參數(shù)是xml解析器缕溉,第二個參數(shù)是要解析布局的父視圖,第三個參數(shù)標識是否需要加入到父視圖中吃型。
上面的inflate方法所做的操作主要有以下幾步:
- 解析xml的根標簽
- 如果根標簽是
merge
证鸥,那么調(diào)用rInflate
解析,將merge
標簽下的所有子View直接添加到根標簽中 - 如果不是merge勤晚,調(diào)用
createViewFromTag
解析該元素 - 調(diào)用
rInflate
解析temp中的子View枉层,并將這些子View添加到temp中 - 通過
attachToRoot
,返回對應(yīng)解析的根視圖
我們先看createViewFromTag
方法:
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
try {
View view;
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
// 通過.來判斷是自定義View還是內(nèi)置View
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
throw ie;
}
}
我們可以發(fā)現(xiàn)赐写,解析View的時候是通過.
來判斷是內(nèi)置的View還是自定義的View的鸟蜡,那么我們就能知道為什么在寫布局文件中自定義的View需要完整路徑了。
在解析內(nèi)置View的時候就是通過類似于PhoneLayoutInflater
的onCreateView
的解析方式挺邀,通過在name
前加上android.view.
最終也是調(diào)用createView
來解析揉忘。
而自定義view則是在調(diào)用createView(name, null, attrs)
時,第二個參數(shù)的前綴傳遞null端铛。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 從緩存中獲取view的構(gòu)造函數(shù)
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
// 如果沒有緩存
if (constructor == null) {
// 如果前綴不為空構(gòu)造完整的View路徑并加載該類
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
// 獲取該類的構(gòu)造函數(shù)
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
// 將構(gòu)造函數(shù)加入緩存中
sConstructorMap.put(name, constructor);
} else {
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通過反射構(gòu)建View
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
}
}
createView
相對簡單泣矛,通過判斷前綴,來構(gòu)建View的完整路徑禾蚕,并將該類加載到虛擬機中您朽,獲取構(gòu)造函數(shù)并緩存,再通過構(gòu)造函數(shù)創(chuàng)建該View對象换淆,并返回哗总。這個時候我們就獲得了根視圖几颜。接著調(diào)用rInflateChildren
方法解析子View,并最終調(diào)用rInflate
方法:
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
// 獲取樹的深度魂奥,通過深度優(yōu)先遍歷
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {// 解析tag標簽
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {// 解析include標簽
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {// 解析到merge標簽菠剩,并報錯
throw new InflateException("<merge /> must be the root element");
} else {
// 解析到普通的子View,并調(diào)用createViewFromTag獲得View對象
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 遞歸解析
rInflateChildren(parser, view, attrs, true);
// 將View加入到父視圖中
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
rInflate
方法通過深度優(yōu)先遍歷的方式來構(gòu)造視圖樹耻煤,當解析到一個View的時候就再次調(diào)用rInflate
方法具壮,直到將路徑下的最后一個元素,并最終將View加入到父視圖中哈蝇。
總結(jié)
- 創(chuàng)建頂層布局
DecorView
棺妓,繼承自FrameLayout
的ViewGroup容器,是PhoneWindow
對象持有的一個實例炮赦,是所有應(yīng)用程序的頂層View怜跑,在系統(tǒng)內(nèi)部進行初始化。 - 在
DecorView
初始化完成后吠勘,系統(tǒng)會根據(jù)應(yīng)用程序的主題特性性芬,在頂層布局中加載基礎(chǔ)布局ViewGroup
,例如R.layout.screen_simple.xml等等剧防,無論如何這個基礎(chǔ)容器中一定會有一個id為android.internal.R.id.content的容器植锉,這個容器是一個FrameLayout
。 - 開發(fā)者通過
contentView
峭拘,將自己的布局添加到基礎(chǔ)布局中的FrameLayout
中