重写 ViewGroup 的 addView 方法

Viewgroup.addView()有5个重载方法:

void	addView(View child, int index, ViewGroup.LayoutParams params)

void	addView(View child, ViewGroup.LayoutParams params)

void	addView(View child, int index)

void	addView(View child)

void	addView(View child, int width, int height)

如果需要想重写addView()实际只需要重写**addView(View child, int index, ViewGroup.LayoutParams params)**即可。

看一下addView的源码:

    public void addView(View child) {
        addView(child, -1);
    }
    
    public void addView(View child, int index) {
        LayoutParams params = child.getLayoutParams();
        if (params == null) {
            params = generateDefaultLayoutParams();
            if (params == null) {
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
            }
        }
        addView(child, index, params);
    }


    public void addView(View child, int width, int height) {
        final LayoutParams params = generateDefaultLayoutParams();
        params.width = width;
        params.height = height;
        addView(child, -1, params);
    }
    
    public void addView(View child, LayoutParams params) {
        addView(child, -1, params);
    }

    /**
     * Adds a child view with the specified layout parameters.
     *
     * @param child the child view to add
     * @param index the position at which to add the child
     * @param params the layout parameters to set on the child
     */
    public void addView(View child, int index, LayoutParams params) {
        // 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();
        addViewInner(child, index, params, false);
    }