一丶View是如何被添加到屏幕窗口上的
將大象裝進(jìn)冰箱需要三步衙猪,創(chuàng)建自定義View也是分為三部曲旱眯。
- 1 創(chuàng)建頂層的布局容器DecorView
- 2 在頂層布局中加載基礎(chǔ)布局的ViewGroup
- 3 將ContentView添加到基礎(chǔ)布局的FrameLayout中
源碼分析,我們這里以Activity為例寻咒。
一般開(kāi)發(fā)中仁锯,我們給Activity設(shè)置布局的入口是setContentView()方法锣杂,進(jìn)入setContentView()方法匙姜。
一·找到setContentView的實(shí)現(xiàn)
/**
* Set the activity content from a layout resource. The resource will be
* inflated, adding all top-level views to the activity.
*
* @param layoutResID Resource ID to be inflated.
*
* @see #setContentView(android.view.View)
* @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
*/
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
這里面我們可以看到畅厢,實(shí)際調(diào)用的是getWindow()的setContenView方法,再來(lái)看看getWindow()方法氮昧,
/**
* Retrieve the current {@link android.view.Window} for the activity.
* This can be used to directly access parts of the Window API that
* are not available through Activity/Screen.
*
* @return Window The current window, or null if the activity is not
* visual.
*/
public Window getWindow() {
return mWindow;
}
返回的是一個(gè)Window對(duì)象框杜。
/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window {
這里Window是一個(gè)抽象類(lèi),從注釋中我們可以看出袖肥,PhoneWindow是Window的唯一實(shí)例咪辱。進(jìn)入PhoneWindow中去查看setContentView()方法。
@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);
}
...
}
這個(gè)方法里面的主要做了兩件事情 installDecor()椎组,mLayoutInflater.inflate(layoutResID, mContentParent)(去解析當(dāng)前出傳入的 布局資源Id)油狂,接下來(lái),我們主要去看下 installDecor()方法,是如何加載一個(gè)DecorView 专筷。
二.了解installDecor()的加載過(guò)程
...
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
...
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-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);
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
...
}
}
}
}
通過(guò)installDecor()源碼的閱讀夹供,主要是做了兩件事。
- 1.generateDecor() 創(chuàng)建一個(gè)DecorView仁堪;
- 2.generateLayout() 將layoutResources(基礎(chǔ)布局)加載到DecorView。
下面來(lái)看一下詳細(xì)過(guò)程:
1.通過(guò)generateDecor方法獲取DecorView(頂層布局)
protected DecorView generateDecor(int featureId) {
...
return new DecorView(context, featureId, this, getAttributes());
}
再看下DecorView的具體實(shí)現(xiàn)填渠。
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
可以看到是DecorView 繼承FrameLayout的容器弦聂,這就說(shuō)明generateDecor()是獲取一個(gè)布局容器。
2.generateLayout()方法是將layoutResource(基礎(chǔ)布局)添加到DecorView
protected ViewGroup generateLayout(DecorView decor) {
// Apply data from current theme. 設(shè)置系統(tǒng)主題的不同樣式和特性
TypedArray a = getWindowStyle();
...
if (mIsFloating) {
...
setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
}
...
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
...
requestFeature(FEATURE_NO_TITLE);
}
...
// Inflate the window decor. 解析decor
int layoutResource; //定義布局的資源變量
int features = getLocalFeatures();
...
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;
}
...
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
...
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
...
return contentParent;
}
1.通過(guò)requestFeature()和setFlags()等方法設(shè)置系統(tǒng)主題的不同樣式和特性氛什。
2.解析窗口View
- 1 . 根據(jù)具體的fetures的不同獲取到系統(tǒng)相應(yīng)的 layoutResources莺葫。
- 2 . 獲取完layoutResource 后,通過(guò)mDecor.onResourcesLoaded()方法去解析這個(gè) layoutResources 枪眉。將解析獲得的view加載到DecorView上捺檬。
3 . 根據(jù)layoutResources (R.layout.screen_simple)上的布局ID:ID_ANDROID_CONTENT 獲取到相應(yīng)的 contentParent(實(shí)際上是一個(gè)R.layout.screen_simple 上的一個(gè)FrameLayout布局)并返回。
步驟一:
1.這里對(duì)不同feature和flags就不做深究了贸铜。
步驟二:
1 . 先通過(guò)fetures獲取相應(yīng)的 layoutResources這里我們假定根據(jù)某些特性條件下獲取到的是 layoutResource = R.layout.screen_simple;
2 . 執(zhí)行onResourcesLoaded()方法堡纬,解析 layoutResources,加載到 DecorView上
先查看源碼 onResourcesLoaded()源碼
void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
...
final View root = inflater.inflate(layoutResource, null);
...
// Put it below the color views.
addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
...
}
在onResourcesLoaded 方法中蒿秦,他通過(guò)解析 layoutResource 創(chuàng)建了一個(gè)root對(duì)象烤镐。 該root對(duì)象例如為: R.layout.screen_simple(系統(tǒng)的xml)。通過(guò)addView方法將 root 對(duì)象加載到DecorView上棍鳖。
步驟三:
在onResourcesLoaded方法執(zhí)行完畢后炮叶,回到 generateLayout()方法中接下來(lái)我們會(huì)獲取到ViewGroup的對(duì)象 contentParent。那么這個(gè)contentParent是什么渡处?
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
首先通過(guò)查看ID_ANDROID_CONTENT 的注釋?zhuān)?我們可以看到這是系統(tǒng)主布局(我們這里假定獲取的是R.layout.screen_simple)一定所具有的ID 镜悉。com.android.internal.R.id.content。
/**
* The ID that the main layout in the XML layout file should have.
*/
public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
我們查看screen_simple.xml医瘫,發(fā)現(xiàn)獲取到這個(gè)contentParent ,實(shí)際上是 screen_simple.xml 上的FrameLayout 侣肄。
<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>
獲取contentParent 并返回后,generateLayout()方法也就執(zhí)行完畢醇份。我們回到installDecor()方法中茫孔。
就此installDecor()的主要方法執(zhí)行完畢。 以上我們可以理解是在這個(gè)過(guò)程是獲取到DecorView被芳,然后將根據(jù)不同特性獲取到的系統(tǒng)的layoutResources加載到DecorView上缰贝。最后我們?cè)俑鶕?jù)ID_ANDROID_CONTENT 從layoutResources獲取到contentParent 。它實(shí)際上是一個(gè)FrameLayout畔濒。
三.加載setContentView中設(shè)置的布局
1.將setContentView中設(shè)置的布局加載到contentParent上
@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);
}
...
}
最后通過(guò):
mLayoutInflater.inflate(layoutResID, mContentParent);
將在activity上設(shè)置的布局 layoutResID 加載到 contentParent上 也就是 FrameLayout上剩晴。至此,我們的整個(gè)View就加載并顯示到屏幕上了。
總結(jié):
view是如何被添加到屏幕窗口上的赞弥?
1.首先系統(tǒng)會(huì)創(chuàng)建一個(gè)頂層布局容器DecorView毅整。DecorView 是一個(gè)ViewGroup容器, 繼承FrameLayout绽左,是PhoneWindow對(duì)象持有的一個(gè)實(shí)例悼嫉,他是所有應(yīng)用程序的頂層View,在系統(tǒng)內(nèi)部進(jìn)行初始化拼窥。當(dāng)DecorView 初始化完成后戏蔑,系統(tǒng)會(huì)根據(jù)應(yīng)用程序的頂層特性會(huì)加載一個(gè)基礎(chǔ)容器,例如no_actionBar等鲁纠,不同的主題加載的基礎(chǔ)容器也不一樣总棵,但是無(wú)論什么樣的的基礎(chǔ)容器一定會(huì)有一個(gè) android.R.di.content 的FrameLayout。開(kāi)發(fā)者通過(guò)setContView設(shè)置的xml 改含,通過(guò)解析后就加載到了這個(gè)FrameLayout中情龄。