您的位置:首页 > 其它

自定义控件ViewGroup

2018-02-13 18:04 85 查看
对于ViewGroup来说就是一个里面放了许多的View的东西。所以想要自定义一个ViewGroup比自定义View要稍微复杂一点。

1.重写onMeasure()方法

2.重写onLauyout()方法

3.处理触摸事件

onMeasure() 跟自定义View一样,需要测量好并给其设置测量好的宽高,但ViewGroup的跟View不太一样的地方在于,View需要测量的是自己,而ViewGroup则是测量自己里面的子View,并根据子View的测量来设置自己的宽高。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

height = 0;
width = MeasureSpec.getSize(widthMeasureSpec);
for (int i = 0; i < getChildCount(); i++) {
//遍历子View,并测量
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
height += child.getMeasuredHeight();
}
setMeasuredDimension(width, height);
}


left:ViewGroup的left到子View的left的距离

top:ViewGroup的top到子View的top的距离

right:ViewGroup的left到子View的right的距离

bottom:ViewGroup的top到子View的bottom的距离。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ViewGroup