android自定义ViewGroup总结

在稍微复杂一些的布局中就要自己定义一个ViewGroup,里面可以放很多不同的View。android的launcher桌面就是一个很典型的例子。有兴趣的同学可以详细研究一个workspace.java类。
1、在新建一个PreviewLayout并继承自ViewGroup时会自己调价重新方法onLayout()这个方法是在你每次想ViewGroup添加View时调用,你可以在这儿设置每个view在Viewgroup中的位置。

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
int childLeft = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View childView = getChildAt(i);
if (childView.getVisibility() != View.GONE) {
final int childWidth = childView.getMeasuredWidth();
childView.layout(childLeft, 0, childLeft + childWidth,
childView.getMeasuredHeight());
childLeft += childWidth;
}
}
}
}

注意:如果你要动态添加View到ViewGroup,要把if(changed)这个判断条件去掉,不去会引起让人蛋疼的VIew不显示问题。
2、光重写onLayout方法是不行的,还要重新onMeasure方法,并给每个View设置大小。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
}

这个很重要,不然你想Viewgroup中添加的View是不会显示的。具体原因还没搞懂,这儿有片文章可以参考一下:http://hi.baidu.com/huareal/blog/item/0aa0e2d587220b2b9b502708.html或者http://hi.baidu.com/qinghua3344521/blog/item/17fead162adb275921a4e977.html
有高手指点一下。
附件里面是一个自定义的ViewGroup,可以左右拖动,类似于launcher桌面,向里面添加View就可以使用!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值