一.前言
ViewGroup相当于一个放置View的容器,我们通过不同子view,你可以按照自己特定的规则去摆放。
通常自定义控件可以分为这么几个阶段
1,准备工作:(加载阶段)
2,规划大小:(测量阶段)
3,绘制位置:(布局阶段)
4,画:(绘制阶段)
而我们的自定义viewGroup一般需要用到前三个步骤
二.简单示例
我们先试做一个最简单的demo,
需求:一个viewGourp里面有且只能有一个子控件,子控件在viewGroup的正中间。
1,准备工作:(加载阶段)
定义一个类继承ViewGroup,构造方法一般这么写
//当需要new当前视图的时候需要重写这个构造
public CircleViewGroup(Context context) {
this(context, null);
}
//当需要将自定义View声明在xml文件中使用的时候需要重写这个构造方法
public CircleViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
//当需要将自定义View声明在xml文件中,并且当前控件需要自定义主题样式的时候.重写这个构造方法
public CircleViewGroup(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
}
这里需求太简单了,没有什么要初始化的,所以没有写方法体。
2,规划大小:(测量阶段)
在测量阶段可以拿到父控件的宽高
注意measureChildren这个方法不写的话是拿不到子view的宽高的
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
parentWidth = MeasureSpec.getSize(widthMeasureSpec);
parentHeight = MeasureSpec.getSize(heightMeasureSpec);
// 计算出所有的childView的宽和高
measureChildren(widthMeasureSpec, heightMeasureSpec);
}
3,绘制位置:(布局阶段)
布局阶段通过摆放子view的左上右下位置来控制子view大小。
如果有多个子view也只拿第一view,其他不做处理。
注意:这里的子view的layout的坐标原点是对应父控件的左上角,所以中心点就是1/2的父控件宽高
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int centerL = (int) (parentWidth/2);
int centerT = (int) (parentHeight/2);
int childCount = getChildCount();
if (childCount>0){
View childview = getChildAt(0);
int childWidth = childview.getMeasuredWidth();
int childHeight = childview.getMeasuredHeight();
childview.layout(centerL-childWidth/2,centerT-childHeight/2,centerL+childWidth/2,centerT+childHeight/2);
}
}
布局文件
<com.example.king.kingcustomview.CircleViewGroup
android:layout_width="200dp"
android:layout_marginLeft="20dp"
android:layout_centerInParent="true"
android:background="#ff0000"
android:layout_height="200dp">
<View
android:layout_width="100dp"
android:layout_height="50dp"
android:background="#00ff00"
></View>
</com.example.king.kingcustomview.CircleViewGroup>
结果
现在我们只是完成了一个最简单的自定义view,下篇文章我们来实现一个稍微复杂一些的自定义viewGroup