Activity中setContentView过程

Activity中setContentView过程Windows概念Android手机中所有的视图都是通过Window来呈现的,像常用的Activity,Dialog,PopupWindow,Toast,他们的视图都是附加在Window上的,所以可以这么说——Window是View的直接管理者。Activity中加载布局Activity中加载布局,都是通过在onCreate中调用setContentView方法开始:

大家好,又见面了,我是你们的朋友全栈君。

Windows概念

  Android手机中所有的视图都是通过Window来呈现的,像常用的Activity,Dialog,PopupWindow,Toast,他们的视图都是附加在Window上的,所以可以这么说 ——Window是View的直接管理者。

Activity中加载布局

Activity中加载布局,都是通过在onCreate中调用setContentView方法开始:

@Override  
protected void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main_layout);  
    ButterKnife.bind(this);  
}  

Activity中有setContentView重载方法,一个是layoutid,一个直接传入view:

public void setContentView(@LayoutRes int layoutResID) {  
       getWindow().setContentView(layoutResID);  
       initWindowDecorActionBar();  
   }  
public void setContentView(View view) {  
       getWindow().setContentView(view);  
       initWindowDecorActionBar();  
   }  
public void addContentView(View view, ViewGroup.LayoutParams params) {
       getWindow().addContentView(view, params);
       initWindowDecorActionBar();
}

实际上调用的都是PhoneWindow的setContentView方法(PhoneWindow是Window的具体实现类)。initWindowDecorActionBar一看就知道是初始化actionbar的 :

@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) {  
        //如果mContentParent为空调用installDecor,初始化
        installDecor();  
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {  
        //如果内容已经加载过(不是第一次加载),并且不需要动画,removeAllViews()
        mContentParent.removeAllViews();  
    }  

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {  
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,  getContext());  
        //添加完Content后如有设置了FEATURE_CONTENT_TRANSITIONS则添加Scene来过度启动
        transitionTo(newScene);  
    } else {              
        //可以看到mContentParent这个view作为layoutResID的parent,所以layoutResID根width/height参数有效 
        mLayoutInflater.inflate(layoutResID, mContentParent);  
    }  
    mContentParent.requestApplyInsets();  
    final Callback cb = getCallback();  
    if (cb != null && !isDestroyed()) {  
        cb.onContentChanged();  
    }  
}  

@Override  
public void setContentView(View view) {  
    //所以始终是MATCH_PARENT,所以该view的width/height无效 
    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) {  
        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 {  
        //把这个view加入到mContentParent中了,同时layoutparam为MATCH_PARENT 
        mContentParent.addView(view, params); 
    }  
    mContentParent.requestApplyInsets();  
    final Callback cb = getCallback();  
    if (cb != null && !isDestroyed()) {  
        cb.onContentChanged();  
    }  
} 

源码中看出mContentParent是在installDecor方法中初始化的:

private void installDecor() {  
       if (mDecor == null) {  
           //初始化mDecor这个View 
           mDecor = generateDecor();
           mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);  
           mDecor.setIsRootNamespace(true);  
           if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {  
               mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);  
           }  
       }  
       if (mContentParent == null) {  
           //通过mDecor对象初始化mContentParent 
           mContentParent = generateLayout(mDecor); 
           .....  
       }  
.....  
}  

可以看到通过generateDecor方法生成了DecorView,这个DecorView其实也是所有应用窗口的根View:

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks { 
   ...}

在generateLayout方法中初始化了mContentParent对象:

protected ViewGroup generateLayout(DecorView decor) {  
        // Apply data from current theme.应用当前theme的数据,下面一连串的if就是根据你设置的theme来判断当前加载的形式的
        TypedArray a = getWindowStyle();  
        .........  
        //设置style为Window_windowNoTitle或者Window_windowActionBar
        if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
            requestFeature(FEATURE_NO_TITLE);
        } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
            // Don't allow an action bar if there is no title.
            requestFeature(FEATURE_ACTION_BAR);
        }
        ....
        //设置是否全屏
        if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
        }
        ......//一大堆if判断style资源
        //这里开始根据gradle中的targetSdkVersion来判断是否需要加载菜单栏
        final Context context = getContext();
        final int targetSdk = context.getApplicationInfo().targetSdkVersion;
        final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
        final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
        final boolean targetHcNeedsOptions = context.getResources().getBoolean(
                R.bool.target_honeycomb_needs_options_menu);
        final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
        if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
            setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
        } else {
            setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
        }
        //高端设备上的非浮动窗口必须放在系统栏下方,因此必须知道这些窗口的可见性变化。
        // Non-floating windows on high end devices must put up decor beneath the system bars and
        // therefore must know about visibility changes of those.
        if (!mIsFloating && ActivityManager.isHighEndGfx()) {
            if (!targetPreL && a.getBoolean(
                    R.styleable.Window_windowDrawsSystemBarBackgrounds,
                    false)) {
                setFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
                        FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS & ~getForcedWindowFlags());
            }
        }
        ......//省略多个if判断
        WindowManager.LayoutParams params = getAttributes();
        ......//省略其他加载资源
        // Inflate the window decor
        //添加布局到DecorView,前面说到,DecorView是继承与FrameLayout,它本身也是一个ViewGroup,
        //而我们前面创建它的时候,只是调用了new DecorView,此时里面并无什么东西。而下面的步奏则是根据
        //用户设置的Feature来创建相应的布局主题。
        //举个例子,如果我在setContentView之前调用了requestWindowFeature(Window.FEATURE_NO_TITLE),
        //这里则会通过getLocalFeatures来获取你设置的feature,进而加载对应的布局,此时是加载没有标题栏的主题.
        //这也就是为什么我们在代码中设置Theme或者requesetFeature()的时候必须在setContentView之前的原因.
        int layoutResource;
        //记得上文中的requestFeature,然后就可以通过getLocalFeatures方法获取了。。其实在activity中可以调用requestFeature 
        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;
        } 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
            ......//一大堆else if条件判断
        } else {
            // Embedded, so no decoration is needed.
            layoutResource = R.layout.screen_simple;    ③
            // System.out.println("Simple!");
        }
        mDecor.startChanging();
        //选择对应布局创建添加到DecorView中
        View in = mLayoutInflater.inflate(layoutResource, null);
        //往DecorView中添加子View,即mContentParent
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));  
        mContentRoot = (ViewGroup) in;
        .........
        //获取id=content的view作为contenparent 
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);   
         .........
        mDecor.finishChanging();
        return contentParent;
   }  

可以看见上面方法主要作用就是根据窗口的风格修饰类型为该窗口选择不同的窗口根布局文件。mDecor做为根视图将该窗口根布局添加进去,然后获取id为content的FrameLayout返回给mContentParent对象。所以installDecor方法实质就是产生mDecor和mContentParent对象。另一方面如果要设置窗口风格,必须放在setContentView的前面:

  • requestWindowFeature(Window.FEATURE_NO_TITLE);//getLocalFeatures方法中被获取
  • setContentView(R.layout.test_layout);

View tree结构图:

这里写图片描述

DecorView果然作为根View,其下有三个子view。id为statusBarBackgroud和id为navigationBarBackground的View,分别表示手机的顶部的状态栏和手机底部的导航栏。然后是一个LinearLayout,这个LinearLayout是根据窗口的风格修饰类型而为该窗口选择不同的窗口根布局文件:上图为窗口风格是NoTitle,同时没有actionbar的时候。

LinearLayout包括一个@+id/action_mode_bar_stub的ViewStub,一个@android:id/content的FrameLayout。在setContentView中,PhoneWindow的setContentView方法中的下面两种方式都把这个FrameLayout作为了main_activity.xml的根视图:
1. mLayoutInflater.inflate(layoutResID, mContentParent);
2. mContentParent.addView(view, params);

inflate内部其实还是调用addview,然后一直如果该view是viewgroup,那么viewgroup又会把其中所有的子view都add进去,所以最后view就形成了一个视图层次。
DecorView是顶级View,它可以标示整个屏幕,其中包含状态栏,导航栏,内容区等等。这里的mContentParent指的是屏幕显示的内容区,而我们设置的activity_main.xml布局实际上是在一个id为content的FrameLayout中的,这个FrameLayout也就是前面一直提到的mContentParent!(我们看源码的话就会发现,不止screen_simple.xml,screen_toobar.xml,screen_title.xml等等布局文件中都含有这个id为content的FrameLayout)

  • screen_simple.xml源码:R.layout.screen_simple就是当我们的theme设置为NoTitleBar时的布局.也就是DecorView下的LinearLayout
<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 
  • screen_title.xml.xml源码:当窗口风格是NoTitle,同时没有actionbar时的布局,也就是DecorView下的LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"; android:orientation="vertical" android:fitsSystemWindows="true">  
    <!-- Popout bar for action modes -->  
    <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: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>  

所有的view的根viewgroup就是上面的decorview,decorview的添加

final void handleResumeActivity(IBinder token,  
        boolean clearHide, boolean isForward, boolean reallyResume) {  
    // If we are getting ready to gc after going to the background, well 
    // we are back active so skip it. 
    ......  
    // TODO Push resumeArgs into the activity for consideration 
    ActivityClientRecord r = performResumeActivity(token, clearHide);  

    if (r != null) {  
        ......  
        // If the window hasn't yet been added to the window manager, 
        // and this guy didn't finish itself or start another activity, 
        // then go ahead and add the window. 
        ......  
        // If the window has already been added, but during resume 
        // we started another activity, then don't yet make the 
        // window visible. 
        ......  
        // The window is now visible if it has been added, we are not 
        // simply finishing, and we are not starting another activity. 
        if (!r.activity.mFinished && willBeVisible  
                && r.activity.mDecor != null && !r.hideForNow) {  
            ......  
            if (r.activity.mVisibleFromClient) {  
                r.activity.makeVisible();  
            }  
        }  
        ......  
    } else {  
        // If an exception was thrown when trying to resume, then 
        // just end this activity. 
        ......  
    }  
}  

handler机制我们知道了启动Activity其实都会启动activityThread的main方法,这个方法里面会创建主线程的looper。启动Activity调用完ActivityThread的main方法之后,接着调用ActivityThread类performLaunchActivity来创建要启动的Activity组件,在创建Activity组件的过程中,还会为该Activity组件创建窗口对象和视图对象;接着Activity组件创建完成之后,通过调用ActivityThread类的handleResumeActivity将它激活。(在onCreate中调用了setContentView,所以把除了decorView之外的所有的view都已经添加进去了。)handleResumeActivity中把decorView添加进去了handleResumeActivity方法中调用了r.activity.makeVisible()。

void makeVisible() {  
    if (!mWindowAdded) {  
        ViewManager wm = getWindowManager(); 
        wm.addView(mDecor, getWindow().getAttributes()); 
        mWindowAdded = true; 
    }  
    mDecor.setVisibility(View.VISIBLE); 
}  

另一方面,wm.addView实际上调用的是WindowManagerGlobal中addView方法,此时创建了ViewRootImpl对象。。ViewRootImpl有木有很熟悉,在绘制View过程中,就是从ViewRootImpl的performTraversals方法开始的,然后依次经过测量,布局,绘制过程。。invalidate其实最后也是调用了ViewRootImpl的performTraversals方法。

public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) {  
      ............  
      ViewRootImpl root;  
      View panelParentView = null;  

............  
      root = new ViewRootImpl(view.getContext(), display);  
      view.setLayoutParams(wparams);  
      mViews.add(view);  
      mRoots.add(root);  
      mParams.add(wparams);  
  }   
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/153253.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • html两个div占满一行,设置div背景色,用float浮动并让键值对形式的文字键右对齐,值左对齐

    html两个div占满一行,设置div背景色,用float浮动并让键值对形式的文字键右对齐,值左对齐

    2021年7月20日
    85
  • 根据美光内存颗粒上的编码查询对应型号

    根据美光内存颗粒上的编码查询对应型号根据美光内存颗粒上的编码查询对应型号今天遇到需要查看美光内存颗粒容量的问题。美光FBGA封装的DDR颗粒上只有两行,每行5位的编码。根据美光官网上的说明,由于FBGA封装上空间的限制,不能印完整的型号信息,只能用编码表示,其中第二行的5位编码可以用于查询对应的型号信息。官方提供了FBGA&ComponentMarkingDecoder工具来查询FBGAcode对应的型号,进而就可以查找到了

    2022年6月22日
    31
  • PCI和PCIE插槽有什么区别?[通俗易懂]

    PCI和PCIE插槽有什么区别?[通俗易懂]PCI是PeripheralComponentInterconnect(外设部件互连标准)的缩写,它是目前个人电脑中使用最为广泛的接口,几乎所有的主板产品上都带有这种插槽。PCI插槽也是主板带有最多数量的插槽类型,在目前流行的台式机主板上,ATX结构的主板一般带有5~6个PCI插槽,而小一点的MATX主板也都带有2~3个PCI插槽,可见其应用的广泛性。PCI是由Intel公司1991年推出的一

    2022年6月29日
    59
  • idea 2021.7激活码【永久激活】

    (idea 2021.7激活码)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月20日
    260
  • DSP FPGA_fpga oddr

    DSP FPGA_fpga oddr序曲:今年(2021年)7月4日至24日,我指导电子信息工程专业18级的12位同学进行小学期的课程实践。多年以来,我一直想鼓励同学们基于国产的FPGA进行设计和实践,今年终于进行了大胆的尝试。为了课程实践顺利进行,我和12位同学提前了近2个月进行准备。从5月17日(周一)早晨8:00第一次讨论会开始,我和12位同学每周都坚持查阅、学习国内FPGA的资料,每周开讨论会研讨学习进展。研讨会辗转于海空学院会议室、控制学院会议室、新图书馆研讨室……由于同学们课多且分散,同时我的其他…

    2022年10月9日
    0
  • NFS服务理解_什么才是最好的服务

    NFS服务理解_什么才是最好的服务概念NFS:NetworkFileSystem网络文件系统,基于内核的文件系统。通过使用NFS,用户和程序可以像访问本地文件一样访问远端系统上的文件,基于RPC(RemoteProcedu

    2022年8月3日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号