由于ViewGroup的直接子类和间接子类比较多,上图描述了展示了部分子类。下面把放在android.widget包下的ViewGroup的全部子类展示出来。
继承关系该写的基本差不多了。下面咱学习一个自定义ViewGroup。
自定义 ViewGroup
=============
ViewGroup常用重写方法
onMeasure()
遍历自己的子View对自己的每一个子View进行measure,绝大多数时候对子View的measure都可以直接用measureChild()这个方法来替代。确定子View的宽高和自己的宽高以后 再调用setMeasuredDimension将ViewGroup自身的宽和高传给它的父View,才可以继续写onLayout()方法。
onSizeChanged()
在onMeasure()后执行,只有大小发生了变化才会执行onSizeChange()。
onLayout()
排列所有子View的位置,通过getChildCount()获取所有子view,getChildAt获取childview调用各自的layout(int l, int t, int r, int b)方法来排列自己。
onDraw()
自定义ViewGroup默认不会触发onDraw方法,需要设置背景色或者setWillNotDraw(false)来手动触发。
注意: ViewGroup的onLayout()方法是必须重写的,而onDraw()方法默认是不会调用。如果想执行onDraw方法,可以通过下面两种方法:
-
1.设置透明背景:
-
在构造函数中:setBackgroundColor(Color.TRANSPARENT);
-
在xml中:android:background=“@color/transparent”
-
2.在构造函数中添加setWillNotDraw(false)不进行自行绘制View。
实例
==
下面咱们写一个简单的栗子,先看效果图。
1.创建CustomLayout继承ViewGroup
/**
* 编写自定义ViewGroup的示例。
*/
public class CustomLayout extends ViewGroup {
// private int childHorizontalSpace = 20;
// private int childVerticalSpace = 20;
private int childHorizontalSpace;
private int childVerticalSpace;
//从代码创建视图时使用的简单构造函数。
public CustomLayout(Context context) {
super(context);
}
//从XML使用视图时调用的构造函数。
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.CustomLa