天天看点

自定义ViewGroup(0)

ViewGroup的职能

Google官网上给出的ViewGroup的功能如下:

*A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams

 class which serves as the base class for layouts parameters.*

简单来说,ViewGroup是一个包含其他view(称之为子View)的特殊View。ViewGroup是布局和view容器的基类。ViewGroup中定义了ViewGroup.LayoutParams作为布局参数的基类。

也就是说,ViewGroup的LayoutParams非常重要。

LayoutParams

LayoutParams are used by views to tell their parents how they want to be laid out.

LayoutParams 是view用来告诉它们的父布局,它们想如何布局的。

LayoutParams 有很多子类,如下图所示。比如MarginLayoutParams,则表明该ViewGroup支持margin,当然这个也可以没有。我们熟悉的LinearLayout.LayoutParams,RelativeLayout.LayoutParams也在其中。

自定义ViewGroup(0)

总得说来,LayoutParams存储了子View在加入ViewGroup中时的一些参数信息。当我们在写xml文件的时候,当在LinearLayout中写childView的时候,我们可以写layout_gravity,layout_weight等属性,但是到了RelativeLayout中,childView就没有了,为什么呢?

**这是因为每个ViewGroup需要指定一个LayoutParams,用于确定支持childView支持哪些属性,比如LinearLayout指定LinearLayout.LayoutParams等。

所以,我们在自定义ViewGroup的时候,一般也需要新建一个新的LayoutParams类继承自ViewGroup.LayoutParams。**

public static class LayoutParams extends ViewGroup.LayoutParams {

  public int left = ;
  public int top = ;

  public LayoutParams(Context arg0, AttributeSet arg1) {
      super(arg0, arg1);
  }

  public LayoutParams(int arg0, int arg1) {
      super(arg0, arg1);
  }

  public LayoutParams(android.view.ViewGroup.LayoutParams arg0) {
      super(arg0);
  }

}
           

自定义的LayoutParams已经有了,那么如何让我们自定义的ViewGroup使用我们自定义的LayoutParams类来添加子View呢,答案是重写generateLayoutParams返回我们自定义的LayoutParams对象即可。

@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(
      AttributeSet attrs) {
  return new MyCustomView.LayoutParams(getContext(), attrs);
}

@Override
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
  return new LayoutParams(LayoutParams.WRAP_CONTENT,
          LayoutParams.WRAP_CONTENT);
}

@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(
      android.view.ViewGroup.LayoutParams p) {
  return new LayoutParams(p);
}

@Override
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
  return p instanceof MyCustomView.LayoutParams;
}
           

自定义ViewGroup的一般步骤

自定义ViewGroup大致有三个步骤measure,layout,draw

- Measure

对于ViewGroup来说,除了要完成自身的measure过程,还要遍历完成子View的measure方法,各个子View再去递归地完成measure过程,但是ViewGroup被定义成了抽象类,ViewGroup里并没有重写onMeasure()方法,而是提供了一个measureChildren()方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int childCount = this.getChildCount();
  for (int i = ; i < childCount; i++) {
      View child = this.getChildAt(i);
      this.measureChild(child, widthMeasureSpec, heightMeasureSpec);
      int cw = child.getMeasuredWidth();
      int ch = child.getMeasuredHeight();
  }
}
           

可以看出,在循环对子View进行measure过程,调用的是measureChild()方法。

protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
           

可以看出,measureChild()方法中通过getChildMeasureSpec()方法,获取子View的childWidthMeasureSpec 和childHeightMeasureSpec,然后传递给子View进行测量。

我们知道,ViewGroup是一个抽象类,它并没有实现onMeasure()方法,所以测量过程的onMeasure()方法就要到各个子类中去实现。

也就是说,在我们自定义的ViewGroup中,我们需要重写onMeasure()方法。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        //自定义ViewGroup的测量在此添加

    }
           

在这里面,直接调用父类的measureChildren()方法,测量所有的子控件的,让然,自定义ViewGroup的测量还有待去完善。

- Layout

Layout的作用是ViewGroup用来确定View的位置,而这都在onLayout()方法中实现,在ViewGroup中,onLayout()方法被定义成了抽象方法,需要在自定义ViewGroup中具体实现。在onLayout()方法中遍历所有子View并调用子View的layout方法完成子View的布局。

@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
  int childCount = this.getChildCount();
  for (int i = ; i < childCount; i++) {
      View child = this.getChildAt(i);
      LayoutParams lParams = (LayoutParams) child.getLayoutParams();
      child.layout(lParams.left, lParams.top, lParams.left + childWidth,
              lParams.top + childHeight);
  }
}
           

其中child.layout(left,top,right,bottom)方法可以对子View的位置进行设置,四个参数的意思大家通过变量名都应该清楚了。

public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != ) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = ; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }
           

可以看到,在layout()方法中, 子View的onLayout()方法又被调用,这样layout()方法就会一层层地调用下去,完成布局。

  • Draw

    draw过程是在View的draw()方法里进行。draw地址分为以下几个过程

(1)drawBackground(canvas):绘制背景

(2)onDraw(canvas) :绘制自己

(3) dispatchDraw(canvas):绘制children

(4)onDrawForeground(canvas):绘制装饰 (foreground, scrollbars)

在自定义View的时候,我们不需要重写draw()方法,只需重写onDraw()方法即可。

值得注意的是ViewGroup容器组件的绘制,当它没有背景时直接调用的是dispatchDraw()方法, 而绕过了draw()方法,当它有背景的时候就调用draw()方法,而draw()方法里包含了dispatchDraw()方法的调用。因此要在ViewGroup上绘制东西的时候往往重写的是dispatchDraw()方法而不是onDraw()方法。