美文网首页
Activity UI加载流程 LayoutInflater布

Activity UI加载流程 LayoutInflater布

作者: 又是那一片天 | 来源:发表于2017-11-28 15:18 被阅读0次

    1. 分析入口为Activity onCreate调用的 setContentView(..)方法

        //Activity类
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    

    2.Activity类中 setContentView(..)调用了 getWindow().setContentView(layoutResID), getWindow()获取了一个Window对象并调用了Window对象的setContentView()方法

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

    Window: 顶级窗口外观和行为策略的抽象基类。这个类的一个实例应该被用作添加到窗口管理器的顶层视图。它提供了标准的UI策略,如背景,标题区域,默认密钥处理等。

    3.Window对象是一个抽象了他的唯一实现是PhoneWindow 其中setContentView(...)才是关键

      //PhoneWindow类
      public void setContentView(int layoutResID) {
            if (mContentParent == null) {//mContentParent  ViewGroup 视图容器 判断是否为空 实际是 DecorView 这是顶View
                installDecor();//初始化DecorView  设置Activity主题
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {//没有动画移除所有View
                mContentParent.removeAllViews();//移除视图
            }
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {//有过度动画 执行动画
                final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                        getContext());
                transitionTo(newScene);
            } else {//初始化布局
                mLayoutInflater.inflate(layoutResID, mContentParent);//解析XML 添加View
            }
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    

    3.1 初始化顶层容器DecorView 初始化后还要设置当前界面 style(样式)添加初始化布局

      //PhoneWindow类
     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);//绑定当前PhoneWindow
            }
            if (mContentParent == null) {
                mContentParent = generateLayout(mDecor);//设置style Activity 样式 并为DecorView初始布局样式
                .....
            }
    }
    
    

    3.2 generateLayout()Activity style实在这里解析配置

        protected ViewGroup generateLayout(DecorView decor) {
            TypedArray a = getWindowStyle();//获取页面当前样式数据 方法如下:
            if (false) {
                System.out.println("From style:");
                String s = "Attrs:";
                for (int i = 0; i < R.styleable.Window.length; i++) {
                    s = s + " " + Integer.toHexString(R.styleable.Window[i]) + "="
                            + a.getString(i);
                }
                System.out.println(s);
            }
    
            mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);//判断当前Window是否是浮窗
            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);
            }
    
            //以下都是设置style 的状态位
            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);
            }
    
            .....
            int layoutResource;//布局文件id
            int features = getLocalFeatures()
    
            //根据主题不一样加载不同的布局文件
            if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
                layoutResource = R.layout.screen_swipe_dismiss;
                setCloseOnSwipeEnabled(true);
            } 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;
                }
    
            ......
             mDecor.startChanging();
            mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);//加载主题布局
    
            ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);//拿到加载程序员布局父容器
            ......
    
            return contentParent;//返回程序员布局容器
    
    
    }
    
        //获取Style解析样式数据
       public final TypedArray getWindowStyle() {
            synchronized (this) {
                if (mWindowStyle == null) {
                    mWindowStyle = mContext.obtainStyledAttributes(
                            com.android.internal.R.styleable.Window);
                }
                return mWindowStyle;
            }
        }
    
    
    Activity布局.png

    4.通过以上过程我们拿到了程序源定义布局文件 父容器 mContentParent (ViewGroup )现在 mLayoutInflater.inflate(layoutResID, mContentParent)接卸自定义布局文件 一直追踪inflate()方法会到达LayoutInflater类中

    LayoutInflater解析xml生成view

    • 先解析布局文件根节点
    //LayoutInflater类
     public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
            final Resources res = getContext().getResources();
            final XmlResourceParser parser = res.getLayout(resource);//Xml解析器
            try {
                return inflate(parser, root, attachToRoot);//调用下面方法
            } finally {
                parser.close();
            }
        }
       //初始化布局文件根节点
      public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
            synchronized (mConstructorArgs) {
                Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
                final Context inflaterContext = mContext;
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                Context lastContext = (Context) mConstructorArgs[0];
                mConstructorArgs[0] = inflaterContext;
                View result = root;
                try {
                    //解析Xml 寻找根节点
                    int type;
                    while ((type = parser.next()) != XmlPullParser.START_TAG &&
                            type != XmlPullParser.END_DOCUMENT) {
                        // Empty
                    }
                    if (type != XmlPullParser.START_TAG) {
                        throw new InflateException(parser.getPositionDescription()
                                + ": No start tag found!");
                    }
    
                    final String name = parser.getName();//获取根节点name
                   if (TAG_MERGE.equals(name)) {//如果节点名merge 
                              if (root == null || !attachToRoot) {//没有根节点 或者 不加载到父布局中 抛出异常
                                  throw new InflateException("<merge /> can be used only with a valid "
                                            + "ViewGroup root and attachToRoot=true");
                              }
                             rInflate(parser, root, inflaterContext, attrs, false);//根节点为merge解析
                       }else{//正常节点
                              final View temp = createViewFromTag(root, name, inflaterContext, attrs);//生成view
                              ViewGroup.LayoutParams params = null;
                              if (root != null) {
                                     params = root.generateLayoutParams(attrs);//调用父布局generateLayoutParams获取LayoutParams
                                    if (!attachToRoot) {//不加入父布局直接设置参数  Adapter因为复用 是由Adapter管理不需要直接加入父布局
                                              temp.setLayoutParams(params);//设置LayoutParams生成的View
                                          }
                                    rInflateChildren(parser, temp, attrs, true);//解析子节点 这个方法最终调用 rInflate();
                                    if (root != null && attachToRoot) {//需要加入父布局 
                                               root.addView(temp, params);//将改节点加入父容器
                                         }
                                      .....
                                }
                        }
                      }
    
    }
    
    • 根节点下的字节点
        void rInflate(XmlPullParser parser, View parent, Context context,
                AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
    
            final int depth = parser.getDepth();
            int type;
            boolean pendingRequestFocus = false;
    
            while (((type = parser.next()) != XmlPullParser.END_TAG ||
                    parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
    
                if (type != XmlPullParser.START_TAG) {
                    continue;
                }
    
                final String name = parser.getName();
    
                if (TAG_REQUEST_FOCUS.equals(name)) {
                    pendingRequestFocus = true;
                    consumeChildElements(parser);
                } else if (TAG_TAG.equals(name)) {
                    parseViewTag(parser, parent, attrs);
                } else if (TAG_INCLUDE.equals(name)) {
                    if (parser.getDepth() == 0) {
                        throw new InflateException("<include /> cannot be the root element");
                    }
                    parseInclude(parser, context, parent, attrs);
                } else if (TAG_MERGE.equals(name)) {
                    throw new InflateException("<merge /> must be the root element");
                } else {
                    final View view = createViewFromTag(parent, name, context, attrs);
                    final ViewGroup viewGroup = (ViewGroup) parent;
                    final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                    rInflateChildren(parser, view, attrs, true);
                    viewGroup.addView(view, params);
                }
            }
    
            if (pendingRequestFocus) {
                parent.restoreDefaultFocus();
            }
    
            if (finishInflate) {
                parent.onFinishInflate();
            }
        }
    
    

    总的逻辑图

    Activity UI加载.png

    总结:

    每一个Activity都有一个关联的Window(PhoneWindow )对象,用来描述程序窗口

    每一个窗口又包含一个DecorView对象,DecorView对象用来描述窗口的视图--XML布局

    相关文章

      网友评论

          本文标题:Activity UI加载流程 LayoutInflater布

          本文链接:https://www.haomeiwen.com/subject/rexdbxtx.html