setContentView流程

setContentView流程1、activity、window、DecorView、ViewRoot之间的预备知识activityactivity是Android的四大组件之一,负责控制activity的生命周期和处理事件,负责视图的添加与显示,以及通过一些回调方法与window和View进行交互。一个activity包含一个window,window才是真正的窗口WindowWindow是一个抽象类,它真正的实现类是PhoneWindow。Window通过WindowManager加载一个DecorView到Window中,

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

1、activity、window、DecorView、ViewRoot之间的预备知识

activity

activity是Android的四大组件之一,负责控制activity的生命周期和处理事件,负责视图的添加与显示,以及通过一些回调方法与window和View进行交互。一个activity包含一个window,window才是真正的窗口

Window

Window是一个抽象类,它真正的实现类是PhoneWindow。Window通过WindowManager加载一个DecorView到Window中,并将DecorView交给ViewRoot。
FrameWork定义了三种窗口类型,三种类型定义在WindowManager,通过LayoutParams.type设置

  • 应用窗口,对应于一个Activity。加载Activity由AmS完成,创建一个应用窗口只能在Activity内部完成(层级1~99)。
  • 子窗口,必须依附于任何类型的父窗口(层级1000~1999)。
  • 系统窗口,不需要对应任何Activity,如:状态栏,导航栏,普通应用程序不能创建系统窗口,必须要有系统应用权限.(层级2000~2999)。

DecorView

DecorView是FrameLayout的子类,它可以被认为是Acitivity的视图根节点。是setContentView所设置的View的父容器。

ViewRoot

ViewRoot对应ViewRootImp类,它是连接WindowManager和DecorView的纽带,在ActivityThread中,当Activity对象创建完毕后,会将DecorView添加到Window中,同时会创建ViewRootImp对象,并将ViewRootImp对象和DecorView建立关联。View的三大流程measure layout draw都是通过ViewRoot完成。ViewRoot并不属于View树的一部分,从源码上看它既非View的子类,也非View的父类,但是它实现了ViewParent接口,所以可以算作名义上的View的父视图。ViewRoot继承了Handler类,Android所有的触屏事件、按键事件、界面刷新等事件都是通过ViewRoot进行分发的.
ViewRootImpl中调用performTraversals方法,然后便开始测量布局绘画了,界面才得以显示出来,这就是View的绘制流程起点。

2、activity、window、decorView的视图层级关系

看下一张图
在这里插入图片描述
上图描述了activity、window、decorView和设置View的视图层级关系

3、setContentView的具体流程源码

先从Activity.java的setContentView()开始

    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

可以看到如下步骤:

  • 获取window(PhoneWindow)
  • 调用PhoneWindow的setContentView方法。
  • 初始化dcorView的ActionBar(3.0推出,目的是为了统一界面风格,现在已经被5.0出的ToolBar取代)

PhoneWindow.java的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 {
            //生成的布局内容添加到 decoView的contentView中去
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        //...
    }

上面的方法中主要就是干了2件事:

  • 初始化安装DecorView
  • 将布局内容通过LayoutInflatert添加到decorView的Content中去。

installDecor()

下面继续看installDecor()方法干了什么

    private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            //创建decorView
            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) {
            //为decorView设置布局样式,并返回mContentParent
            mContentParent = generateLayout(mDecor);

          ....
        }
    }

1、generateDecor()

    protected DecorView generateDecor(int featureId) {
        Context context;
        if (mUseDecorContext) {
            Context applicationContext = getContext().getApplicationContext();
            if (applicationContext == null) {
                context = getContext();
            } else {
                context = new DecorContext(applicationContext, this);
                if (mTheme != -1) {
                    context.setTheme(mTheme);
                }
            }
        } else {
            context = getContext();
        }
        //创建DecorView 
        return new DecorView(context, featureId, this, getAttributes());
    }

generateDecor()的方法很简单,就是获取上下文context,并且实例化DecorView.

2、generateLayout()

    protected ViewGroup generateLayout(DecorView decor) {
        // 现货区当前主题
        TypedArray a = getWindowStyle();

        mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
                & (~getForcedWindowFlags());
        if (mIsFloating) {
            setLayout(WRAP_CONTENT, WRAP_CONTENT);
            setFlags(0, flagsToUpdate);
        } else {
            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
            getAttributes().setFitInsetsSides(0);
            getAttributes().setFitInsetsTypes(0);
        }
        //设置窗口特征,
        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);
        }

        ........
        // Inflate the window decor.
        //根据主题样式,加载布局
        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) {
                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_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();
        //将适配的布局文件生成root,并且调用addView的方法添加到decorview中去
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
       //拿到content通过布局,注意该id的值,获取的就是mContentParent
        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);
            }
        }

        // Remaining setup -- of background and title -- that only applies
        // to top-level windows.
        if (getContainer() == null) {
            mDecor.setWindowBackground(mBackgroundDrawable);

            final Drawable frame;
            if (mFrameResource != 0) {
                frame = getContext().getDrawable(mFrameResource);
            } else {
                frame = null;
            }
            mDecor.setWindowFrame(frame);

            mDecor.setElevation(mElevation);
            mDecor.setClipToOutline(mClipToOutline);

            if (mTitle != null) {
                setTitle(mTitle);
            }

            if (mTitleColor == 0) {
                mTitleColor = mTextColor;
            }
            setTitleColor(mTitleColor);
        }

        mDecor.finishChanging();

        return contentParent;
    }

上面的方法简单的流畅描述下:

  • 先获取当前window的主题样式
  • 根据主题样式找到对象的布局
  • 根据布局样式加载对应的布局到decorView中去
  • 然后通过findViewByid的方法获取到View,返回View即为mContentParent。

注意: 拿到content的过程。上面通过主题加载布局,此次使用R.layout.screen_simple,作为例子来操作下面获取contentParent的过程。

  public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
  
   //拿到content
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

screen_simple不布局内容

<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>

改文件内容很简单一个是ViewStub,此用来是设置actionBar的设置,下面一个FrameLayout对应的id是content,所以 mContentParent的就是framelayout。

到此setContentView的流程大致已经结束。以上是decorView已经创建起来。注意此时的DecorVIew还是不可见的。

4、DecorView的显示

当DecorView的构造流程完成时此时decorView还没有添加到window中。
ActivityThread的handleResumeActivity方法中,首先会调用Activity的onResume方法,接着调用Activity的makeVisible()方法。
makeVisible()中通过WindowManager.addView()完成了DecorView的添加和显示两个过程

 void makeVisible() { 
   
        if (!mWindowAdded) { 
   
            ViewManager wm = getWindowManager();
            //windowManager添加DecorView
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        //设置decorView可见
        mDecor.setVisibility(View.VISIBLE);
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/153247.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

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