Android中整个的View的组装是采用组合模式。

ViewGroup就相当与树根,各种Layout就相当于枝干,各种子View,就相当于树叶。

至于View类。我们就当它是个种子吧。哈哈!

ViewGroup属于树根,可以生长数很多枝干(继承自定义Layout)而枝干上有可以长出很多叶子(TextView,ImageVIew......)

好,闲话少叙,接下来步入正题!

首先,关于View的操作方法,被定义在一个叫做ViewManager的接口中,接口中还有两个方法,分别是移除和更新,这次主要分析addView

public interface ViewManager
    {
        /**
         * Assign the passed LayoutParams to the passed View and add the view to the window.
         * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
         * errors, such as adding a second view to a window without removing the first view.
         * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
         * secondary {@link Display} and the specified display can't be found
         * (see {@link android.app.Presentation}).
         * @param view The view to be added to this window.
         * @param params The LayoutParams to assign to view.
         */
        public void addView(View view, ViewGroup.LayoutParams params);
        public void updateViewLayout(View view, ViewGroup.LayoutParams params);
        public void removeView(View view)
  }

addView在ViewGroup中实现,接下来贴出代码进行分析

    public void addView(View child, LayoutParams params) {
        addView(child, -1, params);
    }

这个方法中调用了自身的addView方法,并且多传递了一个-1,这个-1是View的索引,要插入的位置

    public void addView(View child, int index, LayoutParams params) {
        if (DBG) {
            System.out.println(this + " addView");
        }

        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }

        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
        // therefore, we call requestLayout() on ourselves before, so that the child's request
        // will be blocked at our level
        requestLayout();
        invalidate(true);
        addViewInner(child, index, params, false);
    }

这个方法先是重绘了一下布局,然后调用了addViewInner(child, index, params, false);方法,来把View插入到相应的位置

    private void addViewInner(View child, int index, LayoutParams params,
            boolean preventRequestLayout) {

        if (mTransition != null) {
            // Don't prevent other add transitions from completing, but cancel remove
            // transitions to let them complete the process before we add to the container
            mTransition.cancel(LayoutTransition.DISAPPEARING);
        }

        if (child.getParent() != null) {
            throw new IllegalStateException("The specified child already has a parent. " +
                    "You must call removeView() on the child's parent first.");
        }

        if (mTransition != null) {
            mTransition.addChild(this, child);
        }

        if (!checkLayoutParams(params)) {
            params = generateLayoutParams(params);
        }

        if (preventRequestLayout) {
            child.mLayoutParams = params;
        } else {
            child.setLayoutParams(params);
        }

        if (index < 0) {
            index = mChildrenCount;
        }

        //ViewGroup用一个View类型的数组去维护下边的子view,这个方法就是把view添加到响应的位置上
        addInArray(child, index);

        //绑定插入的view的父容器为当前group
        // tell our children
        if (preventRequestLayout) {
            child.assignParent(this);
        } else {
            child.mParent = this;
        }

        if (child.hasFocus()) {
            requestChildFocus(child, child.findFocus());
        }

        AttachInfo ai = mAttachInfo;
        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
            boolean lastKeepOn = ai.mKeepScreenOn;
            ai.mKeepScreenOn = false;
            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
            if (ai.mKeepScreenOn) {
                needGlobalAttributesUpdate(true);
            }
            ai.mKeepScreenOn = lastKeepOn;
        }

        if (child.isLayoutDirectionInherited()) {
            child.resetRtlProperties();
        }

        dispatchViewAdded(child);

        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
        }

        if (child.hasTransientState()) {
            childHasTransientStateChanged(child, true);
        }

        if (child.getVisibility() != View.GONE) {
            notifySubtreeAccessibilityStateChangedIfNeeded();
        }

        if (mTransientIndices != null) {
            final int transientCount = mTransientIndices.size();
            for (int i = 0; i < transientCount; ++i) {
                final int oldIndex = mTransientIndices.get(i);
                if (index <= oldIndex) {
                    mTransientIndices.set(i, oldIndex + 1);
                }
            }
        }
    }

这个方法先检查一下LayoutParams,看看插入的该view是否存在长宽,如果没有就生成一个默认的LayoutParams

然后判断index是否小于0,小于0就赋值为当前容器中的个数,代表插入到最后一项

随后就调用addInArray方法,来插入View到当前ViewGroup中,插入完成后给该view绑定一下父容器(getParent的值)

随后就是一些焦点,监听的分发,我们仔细分析一下插入方法就好了,就是addInArray

   private void addInArray(View child, int index) {
        View[] children = mChildren;
        final int count = mChildrenCount;
        final int size = children.length;
        if (index == count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, size);
                children = mChildren;
            }
            children[mChildrenCount++] = child;
        } else if (index < count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, index);
                System.arraycopy(children, index, mChildren, index + 1, count - index);
                children = mChildren;
            } else {
                System.arraycopy(children, index, children, index + 1, count - index);
            }
            children[index] = child;
            mChildrenCount++;
            if (mLastTouchDownIndex >= index) {
                mLastTouchDownIndex++;
            }
        } else {
            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
        }
    }

mChildren是ViewGroup中的一个View类型的数组,里边存放了该Group下的所有子View

ARRAY_CAPACITY_INCREMENT这个常量的值是12

首先判断一下mChildren的位置还是否充足,不充足就继续扩充12个位置出来,copy源数组内容进到新数组里,然后再把本次要添加的view放到最后

如果index比count小,说明是插入操作,也是先判断位置是否充足,不充足就扩充并且copy到index处,然后在把剩下的copy到index+1到末尾

这样就把index位置空了出来。就完成了插入操作

插入完成后,系统会重绘界面,你就可以看到你插入的view了。

addView这个方法就分析完了,有什么疑问就可以指出来,错误也一样。共同学习共同进步。

[Android FrameWork 6.0源码学习] ViewGroup的addView函数分析的更多相关文章

  1. [Android FrameWork 6.0源码学习] View的重绘过程之WindowManager的addView方法

    博客首页:http://www.cnblogs.com/kezhuang/p/关于Activity的contentView的构建过程,我在我的博客中已经分析过了,不了解的可以去看一下<[Andr ...

  2. [Android FrameWork 6.0源码学习] LayoutInflater 类分析

    LayoutInflater是用来解析XML布局文件,然后生成对象的ViewTree的工具类.是这个工具类的存在,才能让我们写起Layout来那么省劲. 我们接下来进去刨析,看看里边的奥秘 //调用i ...

  3. [Android FrameWork 6.0源码学习] View的重绘过程之Draw

    View绘制的三部曲,测量,布局,绘画现在我们分析绘画部分测量和布局 在前两篇文章中已经分析过了.不了解的可以去我的博客里找一下 下面进入正题,开始分析调用以及函数原理 private void pe ...

  4. [Android FrameWork 6.0源码学习] View的重绘过程

    View绘制的三部曲,  测量,布局,绘画今天我们分析测量过程 view的测量是从ViewRootImpl发起的,View需要重绘,都是发送请求给ViewRootImpl,然后他组织重绘在重绘的过程中 ...

  5. [Android FrameWork 6.0源码学习] Window窗口类分析

    了解这一章节,需要先了解LayoutInflater这个工具类,我以前分析过:http://www.cnblogs.com/kezhuang/p/6978783.html Window是Activit ...

  6. [Android FrameWork 6.0源码学习] View的重绘过程之Layout

    View绘制的三部曲,测量,布局,绘画现在我们分析布局部分测量部分在上篇文章中已经分析过了.不了解的可以去我的博客里找一下 View的布局和测量一样,都是从ViewRootImpl中发起,ViewRo ...

  7. [Android FrameWork 6.0源码学习] View的重绘ViewRootImpl的setView方法

    博客首页:http://www.cnblogs.com/kezhuang/p/ 本篇文章来分析一下WindowManager的后续工作,也就是ViewRootImpl的setView函数的工作 /i* ...

  8. [Android framework学习] ViewGroup的addView函数分析

    博客首页:http://www.cnblogs.com/kezhuang/p/ Android中整个的View的组装是采用组合模式. ViewGroup就相当与树根,各种Layout就相当于枝干,各种 ...

  9. 【Spark2.0源码学习】-1.概述

          Spark作为当前主流的分布式计算框架,其高效性.通用性.易用性使其得到广泛的关注,本系列博客不会介绍其原理.安装与使用相关知识,将会从源码角度进行深度分析,理解其背后的设计精髓,以便后续 ...

随机推荐

  1. C#打开php链接传参然后接收返回值

    php代码 一.php <?php header("Content-Type:text/html;charset=UTF-8"); $u=$_POST['zdupdate'] ...

  2. Nodejs进阶:核心模块Buffer常用API使用总结

    本文摘录自<Nodejs学习笔记>,更多章节及更新,请访问 github主页地址.欢迎加群交流,群号 197339705. 模块概览 Buffer是node的核心模块,开发者可以利用它来处 ...

  3. 开关调色新世界BP2888电源解决方案

    LED智能方案经过几年的拼杀,已经风靡照明界.但人们渐渐发现,对照明来说,一味追求花哨的功能并不被市场所认同,而其中开关调色,以其简单易操作的特点,已逐步融入广大消费者的生活习惯中.对吸顶灯,面板灯等 ...

  4. 全局精确流量调度新思路-HttpDNS服务详解

    但凡使用域名来给用户提供服务的互联网企业,都或多或少地无法避免在有中国特色的互联网环境中遭遇到各种域名被缓存.用户跨网访问缓慢等问题.那么对于腾讯这样的域名数量在10万级别的互联网公司来讲,域名解析异 ...

  5. python 基础篇 2

    三.对变量.对象与赋值的浅析 1.不记住就完蛋了 1.1 记住:一切数据都是对象 1.2 记住:一切变量都是对数据对象的一个引用 1.3 分析:python内部的引用计数 sys.getrefcoun ...

  6. 全景智慧城市常诚——一个实体商家“自剖”VR全景的势在必得

    谈起"智慧城市",你的心中是否充满了期待?随着互联网的发展,人们对于"智慧城市"的需求越来越迫切.现在想想,我也算是首批入驻全景智慧城市的商家之一了.在各种连锁 ...

  7. Web开发安全小贴士

    想要开发出一个安全的.健壮的Web应用其实是非常困难的, 如果你想要快速开发出一款集使用价值.用户体验度.以及安全性为一身的产品,以下安全步骤很必要!!!     数据库 1.对类似访问令牌.电子邮箱 ...

  8. [C++][OpenGL]自己写GUI(0)——介绍

    文章可转载,转载请注明出处:http://www.cnblogs.com/collectionne/p/6928612.html.文章未完,如果不在博客园(cnblogs)发现本文,请访问前面的链接查 ...

  9. 一天搞定CSS---终篇CSS总结

    虽然说是一天搞定CSS,实际上也没有那么简单.只能说让你快速了解常见的CSS知识,解决基本的页面样式布局和设置. 每个独立的CSS知识点都比较简单,但是它们的应用非常灵活,特别是在综合应用中. 粗略说 ...

  10. HashSet集合

    HashSet特点 1.无序,不允许重复(无序指元素顺序与添加顺序不一致,每次遍历出来的位置不是恒久不变的) 2.HashSet通过调用hashCode()和equals方法来剔除重复 3.HashS ...