Android自定义ViewGroup入门
ViewGroup
ViewGroup是View的容器类,自定义ViewGroup就是继承ViewGroup,重写其中onMeasure()和onLayout()方法。
onMeasure()
onMeasure()这个方法中测量容器的大小,在这里你需要将自定义ViewGroup宽高测量出来,并且在setMeasuredDimension(width, height)方法中传入宽和高。
倘若你给定一个固定的宽高,那么在 onMeasure()中你只需要setMeasuredDimension(width, height)就行了。但是实际情况不可能这样所以需要用getChildAt(int)方法获取到子控件。
下面上代码
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
int height = 0
int width = 0;
//getChildCount()获取ViewGroup子控件个数,for循环遍历getChildAt()获取每一个子控件
for (int i = 0; i < getChildCount(); i++) {
height += getChildAt(i).getMeasuredHeight();//高度相加
if (mp.width > width) {
width = getChildAt(i).getMeasuredWidth();//宽度取最大的子控件宽度
}
}
setMeasuredDimension(width, height);//设置ViewGroup的宽高
}
到这里ViewGroup的宽高就设置好了,然后需要绘制每一个子View该怎么摆放。
onLayout()
在onLayout()绘制每一个子View,需要用到layout方法,四个参数分别为左、上、又、下,参数坐标基于ViewGroup的左上角(即左上角坐标为(0,0))
getChildAt(int i ).layout(int left,int top, int right, int bottom )
不多说直接上代码
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.layout(0, height, child.