本文主要內容是講解一個視圖View或者一個ViewGroup對象是如何添加至應用程式視窗中的。
下文中提到的視窗可泛指我們能看到的介面,包括一個Activity呈現的介面(我們可以將之理解為應用程式視窗),一個Dialog,一個Toast,一個Menu菜單等。
首先對相關類的作用進行一下簡單介紹:
Window 類 位於 /frameworks/base/core/java/android/view/Window.java
說明:該類是一個抽象類別,提供了繪製視窗的一組通用API。可以將之理解為一個載體,各種View在這個載體上顯示。
源檔案(部分)如下:
public abstract class Window { //... //指定Activity視窗的風格類型 public static final int FEATURE_NO_TITLE = 1; public static final int FEATURE_INDETERMINATE_PROGRESS = 5; //設定布局檔案 public abstract void setContentView(int layoutResID); public abstract void setContentView(View view); //請求指定Activity視窗的風格類型 public boolean requestFeature(int featureId) { final int flag = 1<<featureId; mFeatures |= flag; mLocalFeatures |= mContainer != null ? (flag&~mContainer.mFeatures) : flag; return (mFeatures&flag) != 0; } //... }
PhoneWindow類 位於/frameworks/policies/base/phone/com/android/internal/policy/impl/PhoneWindow.java
說明: 該類繼承於Window類,是Window類的具體實現,即我們可以通過該類具體去繪製視窗。並且,該類內部包含了 一個DecorView對象,該DectorView對象是所有應用視窗(Activity介面)的根View。 簡而言之,PhoneWindow類是把一個FrameLayout類即DecorView對象進行一定的封裝,將它作為應用視窗的根View,並提供一組通用的視窗操作介面。
源檔案(部分)如下:
public class PhoneWindow extends Window implements MenuBuilder.Callback { //... // This is the top-level view of the window, containing the window decor. private DecorView mDecor; //該對象是所有應用視窗的根視圖 , 是FrameLayout的子類 //該對象是Activity布局檔案的父視圖,一般來說是一個FrameLayout型的ViewGroup // 同時也是DecorView對象的一個子視圖 // This is the view in which the window contents are placed. It is either // mDecor itself, or a child of mDecor where the contents go. private ViewGroup mContentParent; //設定標題 @Override public void setTitle(CharSequence title) { if (mTitleView != null) { mTitleView.setText(title); } mTitle = title; } //設定背景圖片 @Override public final void setBackgroundDrawable(Drawable drawable) { if (drawable != mBackgroundDrawable || mBackgroundResource != 0) { mBackgroundResource = 0; mBackgroundDrawable = drawable; if (mDecor != null) { mDecor.setWindowBackground(drawable); } } } //... }
DecorView類 該類是PhoneWindow類的內部類
說明: 該類是一個FrameLayout的子類,並且是PhoneWindow的子類,該類就是對普通的FrameLayout進行功能的擴充, 更確切點可以說是修飾(Decor的英文全稱是Decoration,即“修飾”的意思),比如說添加TitleBar(標題列),以及TitleBar上的捲軸等 。最重要的一點是,它是所有應用視窗的根View 。
如下所示 :
DecorView 根視圖結構 DecorView 根視圖形式
源檔案(部分)如下:
private final class DecorView extends FrameLayout { //... //觸摸事件處理 @Override public boolean onTouchEvent(MotionEvent event) { return onInterceptTouchEvent(event); } //... }
打個不恰當比喻吧,Window類相當於一幅畫(抽象概念,什麼畫我們未知) ,PhoneWindow為一副齊白石先生的山水畫 (具體概念,我們知道了是誰的、什麼性質的畫),DecorView則為該山水畫的具體內容(有山、有水、有樹,各種介面)。DecorView呈現在PhoneWindow上。
當系統(一般是ActivityManagerService)配置好啟動一個Activity的相關參數(包括Activity對象和Window對象資訊)後,就會回調Activity的onCreate()方法,在其中我們通過設定setContentView()方法類設定該Activity的顯示介面,整個調用鏈由此鋪墊開來。setContentView()的三個構造方法調用流程本質上是一樣的,我們就分析setContentView(intresId)方法。
Step 1 、Activity.setContentView(int resId) 該方法在Activity類中
該方法只是簡單的回調Window對象,具體為PhoneWindow對象的setContentView()方法實現 。
public void setContentView(int layoutResID) { getWindow().setContentView(layoutResID); } public Window getWindow() { return mWindow; //Window對象,本質上是一個PhoneWindow對象 }
Step 2 、PhoneWindow.setContentView() 該方法在PhoneWindow類中
@Override public void setContentView(int layoutResID) { //是否是第一次調用setContentView方法, 如果是第一次調用,則mDecor和mContentParent對象都為空白 if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mLayoutInflater.inflate(layoutResID, mContentParent); final Callback cb = getCallback(); if (cb != null) { cb.onContentChanged(); } }
該方法根據首先判斷是否已經由setContentView()了擷取mContentParent即View對象 , 即是否是第一次調用該PhoneWindow對象setContentView()方法。如果是第一次調用,則調用installDecor()方法,否則,移除該mContentParent所有的所有子View。最後將我們的資源檔通過LayoutInflater對象轉換為View樹,並且添加至mContentParent視圖中。
PS:因此,在應用程式裡,我們可以多次調用setContentView()來顯示我們的介面。
Step 3 PhoneWindow. installDecor() 該方法在PhoneWindow類中
private void installDecor() { if (mDecor == null) { //mDecor為空白,則建立一個Decor對象 mDecor = generateDecor(); mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); mDecor.setIsRootNamespace(true); } if (mContentParent == null) { //generateLayout()方法會根據視窗的風格修飾,選擇對應的修飾布局檔案 //並且將id為content(android:id="@+id/content")的FrameLayout賦值給mContentParent mContentParent = generateLayout(mDecor); //... }
首先、該方法首先判斷mDecor對象是否為空白,如果不為空白,則調用generateDecor()建立一個DecorView(該類是
FrameLayout子類,即一個ViewGroup視圖) ; generateDecor()方法原型為:
protected DecorView generateDecor() { return new DecorView(getContext(), -1); }
其次、繼續判斷mContentParent對象是否為空白,如果不為空白,則調用generateLayout()方法去建立mContentParent對象。
generateLayout()方法如下:
protected ViewGroup generateLayout(DecorView decor) { // Apply data from current theme. //...1、根據requestFreature()和Activity節點的android:theme="" 設定好 features值 //2 根據設定好的 features值,即特定風格屬性,選擇不同的視窗修飾布局檔案 int layoutResource; //視窗修飾布局檔案 int features = getLocalFeatures(); // System.out.println("Features: 0x" + Integer.toHexString(features)); if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) { if (mIsFloating) { layoutResource = com.android.internal.R.layout.dialog_title_icons; } else { layoutResource = com.android.internal.R.layout.screen_title_icons; } // System.out.println("Title Icons!"); } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 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 = com.android.internal.R.layout.screen_progress; // System.out.println("Progress!"); } //... //3 選定了視窗修飾布局檔案 ,添加至DecorView對象裡,並且指定mcontentParent值 View in = mLayoutInflater.inflate(layoutResource, null); decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 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; }
該方法會做如下事情:
1、根據視窗的風格修飾類型為該視窗選擇不同的視窗布局檔案(根視圖)。這些視窗修飾布局檔案指定一個用來存放Activity自訂布局檔案的ViewGroup視圖,一般為FrameLayout 其id 為: android:id="@android:id/content"。例如視窗修飾類型包括FullScreen(全屏)、NoTitleBar(不含標題列)等。選定視窗修飾類型有兩種:
①、指定requestFeature()指定視窗修飾符,PhoneWindow對象調用getLocalFeature()方法擷取值 ;
②、為我們的Activity配置相應屬性,即android:theme=“”,PhoneWindow對象調用getWindowStyle()方法擷取值。
舉例如下,隱藏標題列有如下方法:requestWindowFeature(Window.FEATURE_NO_TITLE); 或者 為Activity配置xml屬性:android:theme=”@android:style/Theme.NoTitleBar”。
PS:因此,在Activity中必須在setContentView之前調用requestFeature()方法。
確定好視窗風格之後,選定該風格對應的布局檔案,這些布局檔案位於 frameworks/base/core/res/layout/ , 典型的視窗布局檔案有:
R.layout.dialog_titile_icons R.layout.screen_title_icons
R.layout.screen_progress R.layout.dialog_custom_title
R.layout.dialog_title
R.layout.screen_title // 最常用的Activity視窗修飾布局檔案
R.layout.screen_simple //全屏的Activity視窗布局檔案
分析Activity最常用的一種視窗布局檔案,R.layout.screen_title :
<!-- This is an optimized layout for a screen, with the minimum set of features enabled. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:fitsSystemWindows="true"> <FrameLayout android:layout_width="match_parent" android:layout_height="?android:attr/windowTitleSize" style="?android:attr/windowTitleBackgroundStyle"> <TextView android:id="@android:id/title" style="?android:attr/windowTitleStyle" android:background="@null" android:fadingEdge="horizontal" android:gravity="center_vertical" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> <FrameLayout android:id="@android:id/content" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" android:foregroundGravity="fill_horizontal|top" android:foreground="?android:attr/windowContentOverlay" /> </LinearLayout>
該布局檔案很簡單,一個LinearLayout下包含了兩個子FrameLayout視圖,第一個FrameLayout用來顯示標題列(TitleBar),該TextView 視圖id為title (android:id="@android:id/title");第二個FrameLayout用來顯示我們Activity的布局檔案的父視圖, 該FrameLayoutid為content (android:id="@android:id/content") 。
全屏的視窗布局檔案R.layout.screen_simple :
This is an optimized layout for a screen, with the minimum set of features enabled. --> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/content" android:fitsSystemWindows="true" android:foregroundInsidePadding="false" android:foregroundGravity="fill_horizontal|top" android:foreground="?android:attr/windowContentOverlay" />
該布局檔案只有一個FrameLayout,用來顯示我們Activity的布局檔案,該FrameLayout id為 android:id="@android:id/content"
2、前面一步我們確定視窗修飾布局檔案後,mDecor做為根視圖將該視窗布局對應的視圖添加進去,並且擷取id為content 的View,將其賦值給mContentParent對象,即我們前面中提到的第二個FrameLayout。
At Last、產生了mDecor和mContentParent對象後,就將我們的Activity布局檔案直接添加至mContentParent父視圖中即可。
回到 Step 2 中PhoneWindow.setContentView() 該方法在PhoneWindow類中
@Override public void setContentView(int layoutResID) { if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mLayoutInflater.inflate(layoutResID, mContentParent); final Callback cb = getCallback(); if (cb != null) { cb.onContentChanged(); } }
整個過程主要是如何把Activity的布局檔案添加至視窗裡,上面的過程可以概括為:
1、建立一個DecorView對象,該對象將作為整個應用視窗的根視圖
2、建立不同的視窗修飾布局檔案,並且擷取Activity的布局檔案該存放的地方,由該視窗修飾布局檔案內id為content的FrameLayout指定 。
3、將Activity的布局檔案添加至id為content的FrameLayout內。
最後,當AMS(ActivityManagerService)準備resume一個Activity時,會回調該Activity的handleResumeActivity()方法,該方法會調用Activity的makeVisible方法 ,顯示我們剛才建立的mDecor 視圖族。
handleResumeActivity()方法原型如下: 位於ActivityThread 類中
//系統resume一個Activity時,調用此方法 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) { ActivityRecord r = performResumeActivity(token, clearHide); //... if (r.activity.mVisibleFromClient) { r.activity.makeVisible(); } }
makeVisible() 方法原型如下: 位於Activity類中
void makeVisible() { if (!mWindowAdded) { ViewManager wm = getWindowManager(); // 擷取WindowManager對象 wm.addView(mDecor, getWindow().getAttributes()); mWindowAdded = true; } mDecor.setVisibility(View.VISIBLE); //使其處於顯示狀況 }
接下來就是,如何把我們已經建立好的視窗通知給WindowManagerService ,以便它能夠把這個視窗顯示在螢幕上。
關於這方面內容大家可以去看鄧凡平老師的這篇部落格《Android深入淺出之Surface[1] 》
參考資料:
Android中將布局檔案/View添加至視窗過程分析 ---- 從setContentView()談起