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); }
可以看到,就会报错的拉。