美文网首页
Android进阶 (布局绘制流程 一 setContentVi

Android进阶 (布局绘制流程 一 setContentVi

作者: _明川 | 来源:发表于2019-12-26 17:20 被阅读0次

    该文章为本人试图进阶Android 中高级之路的第三篇常识解读源码,后续计划还有Activity 启动流程源码分析 等。该篇文章源码较多,如果时间允许会记录一些相关知识点 面试题。该篇阅读时间:三十分钟 ,Android SDK 版本:9.0 。另重申 此为学习笔记如有不足,请多指教。

    update time : 2019年12月25日19:25:42

    Android进阶 (布局绘制流程 二)

    前言

    以前的两篇源码的文章,HashMap 和 Handler 源码都是相对比较简单的。本人的学习路线也是提前 半个月进行规划和确定,所以前边文章的 基础Java 和 基础Android 知识 到后边的 Android 面试知识进阶 到现在的 源码解读 也是一个循序渐进 越来越难的过程。那么该篇主要对对查看解读setContentView()源码过程的一个学习总结/笔记。

    该篇文章篇幅和个人时间问题暂时只记录到 LayoutInflater层, 算是一个 最简单的 阅读源码的过程,下一篇文章会从 接着该篇文章继续尝试深入阅读 View的绘制流程 。

    大体流程图


    绘制流程

    图片参考地址

    进入正题

    1. setContentView()入口

    进入setContentView 方法,查看 AppCompatActivity 中的方法

    public void setContentView(@LayoutRes int layoutResID) {
        this.getDelegate().setContentView(layoutResID);
    }
        
    @NonNull
    public AppCompatDelegate getDelegate() {
       if (this.mDelegate == null) {
           this.mDelegate = AppCompatDelegate.create(this, this);
       }
       return this.mDelegate;
    }
    

    上述代码不多赘述,我们主要看 AppCompatDelegate.create 方法,进入AppCompatDelegate 后发现为abstract ,我们在 对应发现中找到AppCompatDelegate实现类 AppCompatDelegateImpl

    2.AppCompatDelegateImpl

    public void setContentView(View v) {
            this.ensureSubDecor();
            ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
            contentParent.removeAllViews();
            contentParent.addView(v);
            this.mOriginalWindowCallback.onContentChanged();
        }
    
        public void setContentView(int resId) {
            this.ensureSubDecor();
            ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
            contentParent.removeAllViews();
            LayoutInflater.from(this.mContext).inflate(resId, contentParent);
            this.mOriginalWindowCallback.onContentChanged();
        }
    
        public void setContentView(View v, LayoutParams lp) {
            this.ensureSubDecor();
            ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
            contentParent.removeAllViews();
            contentParent.addView(v, lp);
            this.mOriginalWindowCallback.onContentChanged();
        }
    

    上述代码 我们单独挑一个 方法说就可以,我这里以setContentView(int) 方法
    为例,我们一行一行解读 其中重点是 LayoutInflater.from(this.mContext).inflate(resId, contentParent); inflate部分代码请异步该文章第三部分 和 ensureSubDecor()两个方法

    2.1ensureSubDecor

    private void ensureSubDecor() {
            if (!this.mSubDecorInstalled) {
                //下文详细解读
                this.mSubDecor = this.createSubDecor();
                //如布局前安装了一个标题,现在就把它传播出去
                CharSequence title = this.getTitle();
                if (!TextUtils.isEmpty(title)) {
                    if (this.mDecorContentParent != null) {
                        this.mDecorContentParent.setWindowTitle(title);
                    } else if (this.peekSupportActionBar() != null) {
                        this.peekSupportActionBar().setWindowTitle(title);
                    } else if (this.mTitleView != null) {
                        this.mTitleView.setText(title);
                    }
                }
                //适配尺寸在设备上,一些参数的初始化
                this.applyFixedSizeWindow();
                // 一脸懵逼 空方法
                this.onSubDecorInstalled(this.mSubDecor);
                this.mSubDecorInstalled = true;
                AppCompatDelegateImpl.PanelFeatureState st = this.getPanelState(0, false);
                if (!this.mIsDestroyed && (st == null || st.menu == null)) {
                    this.invalidatePanelMenu(108);
                }
            }
        }
    

    上述代码 部分部分方法的作用已经 在注释中说明,接下来我们看看 createSubDecor 方法

    2.2createSubDecor

    private ViewGroup createSubDecor() {
            // 获取系统的TypedArray,系统主题
            TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme);
            if (!a.hasValue(styleable.AppCompatTheme_windowActionBar)) {
              // 如果没有找到就 报错并释放TypedArray对象
                a.recycle();
                throw new IllegalStateException("You need to use a Theme.AppCompat theme (or descendant) with this activity.");
            } else {
                // 设置各种 Windows 属性  
                if (a.getBoolean(styleable.AppCompatTheme_windowNoTitle, false)) {
                    // requestWindowFeature 方法下边 说 
                    this.requestWindowFeature(1);
                } else if (a.getBoolean(styleable.AppCompatTheme_windowActionBar, false)) {
                    this.requestWindowFeature(108);
                }
                if (a.getBoolean(styleable.AppCompatTheme_windowActionBarOverlay, false)) {
                    this.requestWindowFeature(109);
                }
                if (a.getBoolean(styleable.AppCompatTheme_windowActionModeOverlay, false)) {
                    this.requestWindowFeature(10);
                }
                // 获取界面是否是浮动的 应该类似于 Dialog 的判断
                this.mIsFloating = a.getBoolean(styleable.AppCompatTheme_android_windowIsFloating, false);
                a.recycle();
                // PhoneWindow 是Window的子类 ,在PhoneWindow中完成根布局的准备,也就是创建 DecorView ,下文详细说明
                this.mWindow.getDecorView();
                LayoutInflater inflater = LayoutInflater.from(this.mContext);
                ViewGroup subDecor = null;
                 // 下文都是根据标记来决定inflate哪个layout
                if (!this.mWindowNoTitle) {
                    if (this.mIsFloating) {
                        subDecor = (ViewGroup)inflater.inflate(layout.abc_dialog_title_material, (ViewGroup)null);
                        this.mHasActionBar = this.mOverlayActionBar = false;
                    } else if (this.mHasActionBar) {
                        ....
                } else {
                    if (this.mOverlayActionMode) {
                        subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple_overlay_action_mode, (ViewGroup)null);
                    } else {
                        subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple, (ViewGroup)null);
                    }
                    if (VERSION.SDK_INT >= 21) {
                        ViewCompat.setOnApplyWindowInsetsListener(subDecor, new OnApplyWindowInsetsListener() {
                            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                                int top = insets.getSystemWindowInsetTop();
                                int newTop = AppCompatDelegateImpl.this.updateStatusGuard(top);
                                if (top != newTop) {
                                    insets = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), newTop, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
                                }
    
                                return ViewCompat.onApplyWindowInsets(v, insets);
                            }
                        });
                    } else {
             ((FitWindowsViewGroup)subDecor).setOnFitSystemWindowsListener(new OnFitSystemWindowsListener() {
                            public void onFitSystemWindows(Rect insets) {
                                insets.top = AppCompatDelegateImpl.this.updateStatusGuard(insets.top);
                            }
                        });
                    }
                }
                // 如果viewGroup 最后都没有被赋值 则报错
                if (subDecor == null) {
                    throw new IllegalArgumentException(...);
                } else {
                    if (this.mDecorContentParent == null) {
                        this.mTitleView = (TextView)subDecor.findViewById(id.title);
                    }
                    ViewUtils.makeOptionalFitsSystemWindows(subDecor);
                    ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);
                  // 获取 PhoneWindow中的content布局对象
                    ViewGroup windowContentView = (ViewGroup)this.mWindow.findViewById(16908290);
                    if (windowContentView != null) {
                        while(windowContentView.getChildCount() > 0) {
                            View child = windowContentView.getChildAt(0);
                            windowContentView.removeViewAt(0);
                            contentView.addView(child);
                        }
                        windowContentView.setId(-1);
                        contentView.setId(16908290);
                        if (windowContentView instanceof FrameLayout) {
                            ((FrameLayout)windowContentView).setForeground((Drawable)null);
                        }
                    }
                    this.mWindow.setContentView(subDecor);
                    contentView.setAttachListener(new OnAttachListener() {
                        public void onAttachedFromWindow() {
                        }
                        public void onDetachedFromWindow() {
                            AppCompatDelegateImpl.this.dismissPopups();
                        }
                    });
                    return subDecor;
                }
            }
        }
    
    

    上述代码 说明基本都在 注释中,基本大致流程就是这样 首先获取 界面的Theme ,然后通过 mWindow. getDecorView() 设置PhoneWindow 中的 DecorView ,根据不同的标识 设置 属性。接下来我看 一起看看Window 的 实现类PhoneWindow

    3.PhoneWindow

    上文中的 mWindow 的 实现类就是 PhoneWindow ,虽然还有一个 MockWindow 也是继承类,但是MockWindow 更多 是一个 测试类,所以我们主要 解读 PhoneWindow中相应的方法即可。

    @Override
        public void setContentView(int layoutResID) {
            //根据layout的id加载一个布局,然后通过findViewById(R.id.content)加载出布局中id为content
          // 的FrameLayout赋值给mContentParent,并且将该view添加到mDecor(DecorView)中
            if (mContentParent == null) {
                installDecor();
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                // 不是第一次setContentView 移除掉父容器中所有的view 重新添加
                mContentParent.removeAllViews();
            }
            // 窗口是否需要过渡显示
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                        getContext());
                transitionTo(newScene);
            } else {
                // 核心点,前边的 源码也有很多地方 使用inflate 方法,我们下边跟进
                mLayoutInflater.inflate(layoutResID, mContentParent);
            }
            // mContentParent 本质为 FrameLayout
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    

    我们知道 mContentParent 底层为 FrameLayout 后,基本可以了解到 界面大体布局机构了。如下图:

    image

    上面的ActionBarContextView是标题,不过有些设置是不会显示整个标题的,所以这里只是一种情况,下面的id为content的FrameLayout就是这个mContentParent,你通过setContentView方法传递的视图会放到这个id为content的FrameLayout上面,这样你的Activity就显示了你写的布局视图了,由于第一次创建Activity时mContentParent是空的,所以会走PhoneWindow.installDecor方法。

    3.1 installDecor

    private void installDecor() {
        mForceDecorInstall = false;
        // 继承FrameLayout,是窗口顶级视图,也就是Activity显示View的根View,包含一个TitleView和一个ContentView
        if (mDecor == null) {// 首次为空
            // 创建DecorView(FrameLayout)
            mDecor = generateDecor(-1);
            ...
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {// 第一次setContentView时为空
            // 这个mContentParent就是后面从系统的frameworks\base\core\res\res\layout\目录下加载出来
            // 的layout布局(这个Layout布局加载完成后会添加到mDecor(DecorView)中)中的一个id为content的
            // FrameLayout控件,这个FrameLayout控件用来盛放setContentView传递进来的View
            mContentParent = generateLayout(mDecor);
            ...
            // 判断是否存在id为decor_content_parent的view(我只看到screen_action_bar.xml这个里面有这个id)
            final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                    R.id.decor_content_parent);
            if (decorContentParent != null) {
                ...
                if (mDecorContentParent.getTitle() == null) {
                    // 设置标题
                    mDecorContentParent.setWindowTitle(mTitle);
                }
                ...
            } else {
                // 标题视图
                mTitleView = (TextView) findViewById(R.id.title);
                // 有的布局中是没有id为title的控件的,也就是不显示标题
                if (mTitleView != null) {
                    // 判断是否有不显示标题的特性
                    if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
                        final View titleContainer = findViewById(R.id.title_container);
                        if (titleContainer != null) {
                            titleContainer.setVisibility(View.GONE);
                        } else {
                            mTitleView.setVisibility(View.GONE);
                        }
                        mContentParent.setForeground(null);
                    } else {// 显示标题
                        mTitleView.setText(mTitle);
                    }
                }
            }
            // 设置背景
            if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) {
                mDecor.setBackgroundFallback(mBackgroundFallbackResource);
            }
            ...
        }
    }
    

    上文mDecor是DecorView,继承FrameLayout,也就是Activity显示View的根View,包含一个TitleView和一个ContentView,也就是上面图形中的最外层蓝色的边框所指代的视图,这里第一次加载时也是空的,那么会调用generateDecor函数来创建mDecor (具体通过new DecorView(context, featureId, this, getAttributes())方法创建出来的 DecorView),然后通过generateLayout方法创建mContentParent视图,创建完成后会设置标题,我们接下来看一下 generateLayout 主要的工作。

    3.2 generateLayout

    protected ViewGroup generateLayout(DecorView decor) {
        ...
        // 获取Window的各种属性来设置flag和参数
        TypedArray a = getWindowStyle();
        // 根据之前的flag和feature来加载一个layout资源到DecorView中,并把可以作为容器的View返回
        // 这个layout布局文件在frameworks\base\core\res\res\layout\目录下
        int layoutResource;
        int features = getLocalFeatures();
        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) {
            // 是否为 dialog 的判断
            if (mIsFloating) {
                ...
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            removeFeature(FEATURE_ACTION_BAR);
            // System.out.println("Title Icons!");
        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
            layoutResource = R.layout.screen_progress;
        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
            // mIsFloating 这个表示前边提到过是否为 dailog的
            if (mIsFloating) {
                ...
            } else {
                layoutResource = R.layout.screen_custom_title;
            }
            ...
        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
            if (mIsFloating) {
                ...
            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                layoutResource = a.getResourceId(
                        R.styleable.Window_windowActionBarFullscreenDecorLayout,
                        R.layout.screen_action_bar);
            } else {
                layoutResource = R.layout.screen_title;
            }
            // System.out.println("Title!");
        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
            layoutResource = R.layout.screen_simple_overlay_action_mode;
        } else {
            layoutResource = R.layout.screen_simple;
        }
        mDecor.startChanging();
        // 根据layoutResource(布局id)加载系统中布局文件(Layout)并添加到DecorView中
        // 方法内 创建了标题视图,通过LayoutInflater.inflate加载id为layoutResource的布局文件并赋值给根布局
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
        // contentParent是用来添加Activity中布局的父布局(FrameLayout),并带有相关主题样式,就是上面
        // 提到的id为content的FrameLayout,返回后会赋值给PhoneWindow中的mContentParent
        ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }
        ...
        mDecor.finishChanging();
        return contentParent;
    }
    

    这一部分代码 主要作用都在 注释中说的差不多了,根据传入的 DecorView 对他进行 layout 内容的加载。

    这篇文章下半部分主要 引出 LayoutInflater.inflate 这个方法做的事情。
    至于View和 ViewRootImpl 部分放到下一篇文章解读

    接下来我们一起 一探究竟 看看LayoutInflater.inflate 如何将XML布局文件实例化为相应的 View 对象

    4 LayoutInflater.inflate

    Instantiates a layout XML file into its corresponding {@link android.view.View}
    objects. It is never used directly. Instead, use
    {@link android.app.Activity#getLayoutInflater()} or
    {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
    that is already hooked up to the current context and correctly configured
    for the device you are running on.

    翻译:

    将布局XML文件实例化为其相应的{@link android.view.View}
    对象。 永远不要直接使用它。 相反,使用
    {@link android.app.Activity#getLayoutInflater()}或
    {@link Context#getSystemService}检索标准LayoutInflater实例
    已经连接到当前上下文并已正确配置
    对于您正在运行的设备。

    通过 上述备注已经可以引申到 LayoutInflater.inflate 如何初始化的几种方法:

    1. Activity.getLayoutInflater();
    2. Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
    3. LayoutInflater.from(context);

    通过查看源码Activity.getLayoutInflater() 最终会调用到 PhoneWindow 的构造方法,实际上最终调用的就是3;而3最终会调用到2 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;

    那么我们通过 inflate 最终调用的方法来查看下 源码做的工作:

    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 {
                    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();
                    // 如果是Merge标签,则必须依附于一个RootView,
                    if (TAG_MERGE.equals(name)) {
                        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);
                    } else {
                        // Temp 就是通过方法找到的根view
                        final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                        ViewGroup.LayoutParams params = null;
                        if (root != null) {
                            // 如果设置的Root不为null,则根据当前标签的参数生成LayoutParams
                            params = root.generateLayoutParams(attrs);
                            if (!attachToRoot) {
                                // 注意:此处的params只有当被添加到一个Viewz中的时候才会生效;
                                // 如果是null 则设置 params 到 根布局
                                temp.setLayoutParams(params);
                            }
                        }
                        //为 temp 增加children tag内容
                        rInflateChildren(parser, temp, attrs, true);
                        // 如果Root不为null且是attachToRoot,则添加创建出来的View到Root 中
                        if (root != null && attachToRoot) {
                            root.addView(temp, params);
                        }
                        // 判断返回 根布局对象
                        if (root == null || !attachToRoot) {
                            result = temp;
                        }
                    }
                } catch (XmlPullParserException e) {
                    final InflateException ie = new InflateException(e.getMessage(), e);
                    ie.setStackTrace(EMPTY_STACK_TRACE);
                    throw ie;
                } catch (Exception e) {
                    final InflateException ie = new InflateException(parser.getPositionDescription()
                            + ": " + e.getMessage(), e);
                    ie.setStackTrace(EMPTY_STACK_TRACE);
                    throw ie;
                } finally {
                    mConstructorArgs[0] = lastContext;
                    mConstructorArgs[1] = null;
                    Trace.traceEnd(Trace.TRACE_TAG_VIEW);
                }
                return result;
            }
        }
    

    简单梳理一下上述 代码
    如果root为null,attachToRoot将失去作用,设置任何值都没有意义;
    如果root不为null,attachToRoot为true,则会给加载的布局文件的指定一个父布局,即root;
    如果root不为null,attachToRoot为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效;
    在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true;

    4.1 rInflate

    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)) {
                    // 如果这里出现了include标签,就会抛出异常
                    if (parser.getDepth() == 0) {
                        throw new InflateException("<include /> cannot be the root element");
                    }
                    parseInclude(parser, context, parent, attrs);
                } else if (TAG_MERGE.equals(name)) {
                    // 同理如果这里出现了merge标签,也会抛出异常
                    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);
                    // 如果当前View是ViewGroup(包裹了别的View)则在此处inflate其所有的子View
                    rInflateChildren(parser, view, attrs, true);
                    viewGroup.addView(view, params);
                }
            }
            if (pendingRequestFocus) {
                parent.restoreDefaultFocus();
            }
            if (finishInflate) {
              // 回调 父类方法
                parent.onFinishInflate();
            }
        }
    

    在上文代码中 首先判断了View 的状态,并对include、merge标签是否存在进行判断,通过createViewFromTag创建出View对象,之后通过 rInflateChildren 和 rInflate 方法 ,如果发现View 为 ViewGroup则不断地轮训 将所有的 子view 添加到 根布局下*。

    4.2 createViewFromTag

    上文 createViewFromTag() 对于我们还是未知的,我们将源码简单 剖析一下:

    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
                boolean ignoreThemeAttr) {
            if (name.equals("view")) {
                name = attrs.getAttributeValue(null, "class");
            }
            // Apply a theme wrapper, if allowed and one is specified.
            if (!ignoreThemeAttr) {
                final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
                final int themeResId = ta.getResourceId(0, 0);
                if (themeResId != 0) {
                    context = new ContextThemeWrapper(context, themeResId);
                }
                ta.recycle();
            }
            if (name.equals(TAG_1995)) {
                // Let's party like it's 1995!
                return new BlinkLayout(context, attrs);
            }
            try {
                View view;
                // 接下来的判断 如果判断对象存在则调用对应的 onCreateView 方法。
                if (mFactory2 != null) {
                    view = mFactory2.onCreateView(parent, name, context, attrs);
                } else if (mFactory != null) {
                    view = mFactory.onCreateView(name, context, attrs);
                } else {
                    view = null;
                }
    
                if (view == null && mPrivateFactory != null) {
                    // mPrivateFactory 如果不为空则调用 其onCreateView方法
                    view = mPrivateFactory.onCreateView(parent, name, context, attrs);
                }
                // 如果前边几步判断后 都没有复制,则自己创建view
                if (view == null) {
                    final Object lastContext = mConstructorArgs[0];
                    mConstructorArgs[0] = context;
                    try {
                        if (-1 == name.indexOf('.')) {
                            // 如果View的name中不包含 '.' 则说明是系统控件,会在接下来的调用链在name前面加上 'android.view.'
                            view = onCreateView(parent, name, attrs);
                        } else {
                            // 如果name中包含 '.' 则直接调用createView方法,onCreateView 后续也是调用了createView
                            view = createView(name, null, attrs);
                        }
                    } finally {
                        mConstructorArgs[0] = lastContext;
                    }
                }
                return view;
            } catch (InflateException e) {
                throw e;
            } catch (ClassNotFoundException e) {
                .....
            } catch (Exception e) {
                .....
            }
        }
    

    上述主要代码 都有注释标注,唯一没有说明的 便是 createView方法礼拜呢到底是怎么通过 控件名称 和 AttributeSet 获取到view 呢?

    4.3 createView

    public final View createView(String name, String prefix, AttributeSet attrs)
                throws ClassNotFoundException, InflateException {
            Constructor<? extends View> constructor = sConstructorMap.get(name);
            if (constructor != null && !verifyClassLoader(constructor)) {
                constructor = null;
                sConstructorMap.remove(name);
            }
            Class<? extends View> clazz = null;
            try {
                Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
                if (constructor == null) {
                    // 判断 缓存
                    clazz = mContext.getClassLoader().loadClass(
                            prefix != null ? (prefix + name) : name).asSubclass(View.class);
                    if (mFilter != null && clazz != null) {
                        boolean allowed = mFilter.onLoadClass(clazz);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    }
                    constructor = clazz.getConstructor(mConstructorSignature);
                    constructor.setAccessible(true);
                    sConstructorMap.put(name, constructor);
                } else {
                    if (mFilter != null) {
                        Boolean allowedState = mFilterMap.get(name);
                        if (allowedState == null) {
                            // New class -- remember whether it is allowed
                            clazz = mContext.getClassLoader().loadClass(
                                    prefix != null ? (prefix + name) : name).asSubclass(View.class);
                            boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                            mFilterMap.put(name, allowed);
                            if (!allowed) {
                                failNotAllowed(name, prefix, attrs);
                            }
                        } else if (allowedState.equals(Boolean.FALSE)) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    }
                }
                Object lastContext = mConstructorArgs[0];
                if (mConstructorArgs[0] == null) {
                    mConstructorArgs[0] = mContext;
                }
                Object[] args = mConstructorArgs;
                args[1] = attrs;
                // 通过反射 获取 view
                final View view = constructor.newInstance(args);
                if (view instanceof ViewStub) {
                    final ViewStub viewStub = (ViewStub) view;
                    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
                }
                mConstructorArgs[0] = lastContext;
                return view;
            } catch (NoSuchMethodException e) {
                  ......
            } catch (ClassCastException e) {
                .....
            } catch (ClassNotFoundException e) {
                throw e;
            } catch (Exception e) {
                    ......
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
        }
    

    看完 上述代码 基本可以梳理一下 LayoutInflater 中创建View 的过程了,首先通过读取 XML ,使用 Pull 解析方式获取 View 的标签;
    通过标签以反射的方式来创建 View 对象;
    如果是 ViewGroup 的话则会对子 View 遍历并重复以上步骤,然后 add 到父 View 中;
    方法顺序:inflate -> rInflate -> createViewFromTag-> createView

    到这里其实 整个布局 绘制流程已经大概清除了 ,

    相关文章

      网友评论

          本文标题:Android进阶 (布局绘制流程 一 setContentVi

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