`

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就可以使用!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics