addView控制层级源码解析

addView 有多个构造方法,其中

addView(View child, int index, LayoutParams params)第二个参数可以控制需要添加到的层级。

其他没有index参数的方法,其实还是会执行这个带有index参数的方法,只不过默认为-1。比如

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

对于index参数源码的解释为

* @param index the position at which to add the child or -1 to add last

也就是-1到最多。

默认为-1,也就是在最外层。

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方法传入了index,进去看一看。

里面有一句

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

addInArray(child, index);

如果index < 0其实也就是-1.那么就index就为子view的数量,也就是最外层。

那么如果调皮的传了一个很大的值,会怎么处理呢?进去addInArray(child, index);看一看

if (index == count) {
....
}else if (index < count) {
.....
}else {
    throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
}

可以看到,就会报错的拉。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值