zoukankan      html  css  js  c++  java
  • Android中将布局文件/View添加至窗口过程分析 从setContentView()谈起 .

    转载请注明出处:http://blog.csdn.net/qinjuning     

     

     

     

             本文主要内容是讲解一个视图View或者一个ViewGroup对象是如何添加至应用程序窗口中的。

     

            下文中提到的窗口可泛指能看到的界面,包括一个Activity呈现的界面(我们可以将之理解为应用程序窗口),一个Dialog,

       一个Toast,一个Menu菜单等。

     

          首先对相关类的作用进行一下简单介绍:

     

             Window 类   位于 /frameworks/base/core/java/android/view/Window.java

                说明:该类是一个抽象类,提供了绘制窗口的一组通用API。可以将之理解为一个载体,各种View在这个载体上显示。

                 源文件(部分)如下:

    1. public abstract class Window {    
    2.     //...   
    3.     //指定Activity窗口的风格类型   
    4.     public static final int FEATURE_NO_TITLE = 1;  
    5.     public static final int FEATURE_INDETERMINATE_PROGRESS = 5;  
    6.       
    7.     //设置布局文件   
    8.     public abstract void setContentView(int layoutResID);  
    9.   
    10.     public abstract void setContentView(View view);  
    11.   
    12.     //请求指定Activity窗口的风格类型   
    13.     public boolean requestFeature(int featureId) {  
    14.         final int flag = 1<<featureId;  
    15.         mFeatures |= flag;  
    16.         mLocalFeatures |= mContainer != null ? (flag&~mContainer.mFeatures) : flag;  
    17.         return (mFeatures&flag) != 0;  
    18.     }      
    19.     //...   
    20. }  

           PhoneWindow类  位于/frameworks/policies/base/phone/com/android/internal/policy/impl/PhoneWindow.java

             说明: 该类继承于Window类,是Window类的具体实现,即我们可以通过该类具体去绘制窗口。并且,该类内部包含了

                一个DecorView对象,该DectorView对象是所有应用窗口(Activity界面)的根View。 简而言之,PhoneWindow类是

                把一个FrameLayout类即DecorView对象进行一定的包装,将它作为应用窗口的根View,并提供一组通用的窗口操作

                接口。

                   源文件(部分)如下:          

    1. public class PhoneWindow extends Window implements MenuBuilder.Callback {  
    2.     //...   
    3.     // This is the top-level view of the window, containing the window decor.   
    4.     private DecorView mDecor;  //该对象是所有应用窗口的根视图 , 是FrameLayout的子类   
    5.       
    6.     //该对象是Activity布局文件的父视图,一般来说是一个FrameLayout型的ViewGroup    
    7.     // 同时也是DecorView对象的一个子视图   
    8.     // This is the view in which the window contents are placed. It is either   
    9.     // mDecor itself, or a child of mDecor where the contents go.   
    10.     private ViewGroup mContentParent;   
    11.       
    12.     //设置标题   
    13.     @Override  
    14.     public void setTitle(CharSequence title) {  
    15.         if (mTitleView != null) {  
    16.             mTitleView.setText(title);  
    17.         }  
    18.         mTitle = title;  
    19.     }  
    20.     //设置背景图片   
    21.     @Override  
    22.     public final void setBackgroundDrawable(Drawable drawable) {  
    23.         if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {  
    24.             mBackgroundResource = 0;  
    25.             mBackgroundDrawable = drawable;  
    26.             if (mDecor != null) {  
    27.                 mDecor.setWindowBackground(drawable);  
    28.             }  
    29.         }  
    30.     }  
    31.     //...       
    32. }  

           DecorView类    该类是PhoneWindow类的内部类

             说明: 该类是一个FrameLayout的子类,并且是PhoneWindow的子类,该类就是对普通的FrameLayout进行功能的扩展,

                更确切点可以说是修饰(Decor的英文全称是Decoration,即“修饰”的意思),比如说添加TitleBar(标题栏),以及

                TitleBar上的滚动条等 。最重要的一点是,它是所有应用窗口的根View 。

             如下所示 :

       

                   

               DecorView 根视图结构                                                          DecorView 根视图形式

         

         源文件(部分)如下:

    1. private final class DecorView extends FrameLayout {  
    2.     //...   
    3.     //触摸事件处理   
    4.     @Override  
    5.     public boolean onTouchEvent(MotionEvent event) {  
    6.         return onInterceptTouchEvent(event);  
    7.     }  
    8.     //...   
    9. }  


     

           打个不恰当比喻吧,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()方法实现 。

    1. public void setContentView(int layoutResID) {  
    2.     getWindow().setContentView(layoutResID);  
    3. }  
    4.   
    5. public Window getWindow() {  
    6.     return mWindow;   //Window对象,本质上是一个PhoneWindow对象   
    7. }  

      

      Step 2  、PhoneWindow.setContentView()      该方法在PhoneWindow类中  

    1. <span style="font-family:Microsoft YaHei;font-size:16px;"> </span><pre class="java" name="code">@Override  
    2. public void setContentView(int layoutResID) {  
    3.     //是否是第一次调用setContentView方法, 如果是第一次调用,则mDecor和mContentParent对象都为空   
    4.     if (mContentParent == null) {  
    5.         installDecor();  
    6.     } else {  
    7.         mContentParent.removeAllViews();  
    8.     }  
    9.     mLayoutInflater.inflate(layoutResID, mContentParent);  
    10.     final Callback cb = getCallback();  
    11.     if (cb != null) {  
    12.         cb.onContentChanged();  
    13.     }  
    14. }  


         该方法根据首先判断是否已经由setContentView()了获取mContentParent即View对象 , 即是否是第一次调用该

    
    

        PhoneWindow对象setContentView()方法。如果是第一次调用,则调用installDecor()方法,否则,移除该mContentParent

        所有的所有子View。最后将我们的资源文件通过LayoutInflater对象转换为View树,并且添加至mContentParent视图中。

           

            PS:因此,在应用程序里,我们可以多次调用setContentView()来显示我们的界面

     

      Step 3 PhoneWindow. installDecor()    该方法在PhoneWindow类中 

    1. private void installDecor() {  
    2.     if (mDecor == null) {  
    3.         //mDecor为空,则创建一个Decor对象   
    4.         mDecor = generateDecor();  
    5.         mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);  
    6.         mDecor.setIsRootNamespace(true);  
    7.     }  
    8.     if (mContentParent == null) {  
    9.         //generateLayout()方法会根据窗口的风格修饰,选择对应的修饰布局文件   
    10.         //并且将id为content(android:id="@+id/content")的FrameLayout赋值给mContentParent   
    11.         mContentParent = generateLayout(mDecor);  
    12.           
    13.         //...   
    14. }  

        首先、该方法首先判断mDecor对象是否为空,如果不为空,则调用generateDecor()创建一个DecorView(该类是

               FrameLayout子类,即一个ViewGroup视图) ;  generateDecor()方法原型为:

    1. protected DecorView generateDecor() {  
    2.     return new DecorView(getContext(), -1);  
    3. }  

    其次、继续判断mContentParent对象是否为空,如果不为空,则调用generateLayout()方法去创建mContentParent对象。

          generateLayout()方法如下:

     

    1. protected ViewGroup generateLayout(DecorView decor) {  
    2.     // Apply data from current theme.   
    3.   
    4.     //...1、根据requestFreature()和Activity节点的android:theme="" 设置好 features值   
    5.       
    6.     //2 根据设定好的 features值,即特定风格属性,选择不同的窗口修饰布局文件   
    7.     int layoutResource;  //窗口修饰布局文件     
    8.     int features = getLocalFeatures();  
    9.     // System.out.println("Features: 0x" + Integer.toHexString(features));   
    10.     if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {  
    11.         if (mIsFloating) {  
    12.             layoutResource = com.android.internal.R.layout.dialog_title_icons;  
    13.         } else {  
    14.             layoutResource = com.android.internal.R.layout.screen_title_icons;  
    15.         }  
    16.         // System.out.println("Title Icons!");   
    17.     } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0) {  
    18.         // Special case for a window with only a progress bar (and title).   
    19.         // XXX Need to have a no-title version of embedded windows.   
    20.         layoutResource = com.android.internal.R.layout.screen_progress;  
    21.         // System.out.println("Progress!");   
    22.     }   
    23.     //...   
    24.       
    25.     //3 选定了窗口修饰布局文件 ,添加至DecorView对象里,并且指定mcontentParent值   
    26.     View in = mLayoutInflater.inflate(layoutResource, null);  
    27.     decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));  
    28.   
    29.     ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);  
    30.     if (contentParent == null) {  
    31.         throw new RuntimeException("Window couldn't find content container view");  
    32.     }  
    33.   
    34.     if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {  
    35.         ProgressBar progress = getCircularProgressBar(false);  
    36.         if (progress != null) {  
    37.             progress.setIndeterminate(true);  
    38.         }  
    39.     }  
    40.     //...   
    41.     return contentParent;  
    42. }  

     

         该方法会做如下事情:

           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  :

    1. <!--  
    2. This is an optimized layout for a screen, with the minimum set of features  
    3. enabled.  
    4. -->  
    5.   
    6. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    7.     android:orientation="vertical"  
    8.     android:fitsSystemWindows="true">  
    9.     <FrameLayout  
    10.         android:layout_width="match_parent"   
    11.         android:layout_height="?android:attr/windowTitleSize"  
    12.         style="?android:attr/windowTitleBackgroundStyle">  
    13.         <TextView android:id="@android:id/title"   
    14.             style="?android:attr/windowTitleStyle"  
    15.             android:background="@null"  
    16.             android:fadingEdge="horizontal"  
    17.             android:gravity="center_vertical"  
    18.             android:layout_width="match_parent"  
    19.             android:layout_height="match_parent" />  
    20.     </FrameLayout>  
    21.     <FrameLayout android:id="@android:id/content"  
    22.         android:layout_width="match_parent"   
    23.         android:layout_height="0dip"  
    24.         android:layout_weight="1"  
    25.         android:foregroundGravity="fill_horizontal|top"  
    26.         android:foreground="?android:attr/windowContentOverlay" />  
    27. </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 :

    1. This is an optimized layout for a screen, with the minimum set of features  
    2. enabled.  
    3. -->  
    4.   
    5. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    6.     android:id="@android:id/content"  
    7.     android:fitsSystemWindows="true"  
    8.     android:foregroundInsidePadding="false"  
    9.     android:foregroundGravity="fill_horizontal|top"  
    10.     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类中

     

    1. @Override  
    2. public void setContentView(int layoutResID) {  
    3.     if (mContentParent == null) {  
    4.         installDecor();  
    5.     } else {  
    6.         mContentParent.removeAllViews();  
    7.     }  
    8.     mLayoutInflater.inflate(layoutResID, mContentParent);  
    9.     final Callback cb = getCallback();  
    10.     if (cb != null) {  
    11.         cb.onContentChanged();  
    12.     }  
    13. }  

     

     

          整个过程主要是如何把Activity的布局文件添加至窗口里,上面的过程可以概括为:

                  1、创建一个DecorView对象,该对象将作为整个应用窗口的根视图

                  2、创建不同的窗口修饰布局文件,并且获取Activity的布局文件该存放的地方,由该窗口修饰布局文件内id为content的

                      FrameLayout指定 。

                  3、将Activity的布局文件添加至id为content的FrameLayout内。

     

     

     

    最后,当AMS(ActivityManagerService)准备resume一个Activity时,会回调该Activity的handleResumeActivity()方法,

    该方法会调用Activity的makeVisible方法 ,显示我们刚才创建的mDecor 视图族。

     

    handleResumeActivity()方法原型如下: 位于ActivityThread 类中

    1. //系统resume一个Activity时,调用此方法   
    2. final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {  
    3.     ActivityRecord r = performResumeActivity(token, clearHide);  
    4.     //...   
    5.      if (r.activity.mVisibleFromClient) {  
    6.          r.activity.makeVisible();  
    7.      }  
    8. }  


     

     makeVisible() 方法原型如下: 位于Activity类中

    1. void makeVisible() {  
    2.     if (!mWindowAdded) {  
    3.         ViewManager wm = getWindowManager();   // 获取WindowManager对象   
    4.         wm.addView(mDecor, getWindow().getAttributes());  
    5.         mWindowAdded = true;  
    6.     }  
    7.     mDecor.setVisibility(View.VISIBLE); //使其处于显示状况   
    8. }  
    9.       


     

     

            接下来就是,如何把我们已经创建好的窗口通知给WindowManagerService ,以便它能够把这个窗口显示在屏幕上。

  • 相关阅读:
    mybatis 入门基础
    spring学习总结
    综合练习:词频统计
    组合数据类型综合练习
    Python基础综合练习
    熟悉常用的Linux操作
    1.大数据概述
    C程序语法(无左递归)
    文法规则
    实验一词法分析报告
  • 原文地址:https://www.cnblogs.com/rollrock/p/2341361.html
Copyright © 2011-2022 走看看