android 在XML向ViewGroup中添加组件

来源:互联网 发布:淘宝定时开售怎么设置 编辑:程序博客网 时间:2024/05/17 04:47

需要在代码中进行相应的设置:

ViewGroup中的onMeasure方法里添加一个对子元素的遍历,并且在onLayout中添加一个布局遍历就实现了简单的布局了。

下面给出代码:


 @Override   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {      // TODO Auto-generated method stub      super.onMeasure(widthMeasureSpec, heightMeasureSpec);      int childCount = getChildCount();      for(int i = 0; i < childCount; i ++){         View v = getChildAt(i);         v.measure(widthMeasureSpec, heightMeasureSpec);      }   }

@Override   protected void onLayout(boolean changed, int l, int t, int r, int b) {      int childCount = getChildCount();      for(int i = 0; i < childCount; i ++){         View v = getChildAt(i);         v.layout(l, t, r, b);      }   }


其实我们有三种在XML布局中使用ViewGroup的方法:

 

1、直接使用ViewGroup

这个方法是在自己写的ViewGroup中通过addView方法一个一个添加子View,这样使用很不智能,但是不可否认这样使用有其独挡一面的地方。

 

2、在XML中向ViewGroup中添加View

通过在xml文件中配置锁包含的view

 

3、混合布局

既使用XML中声明的ViewGroup中添加View,又在自己写的类中添加View,上述两种的结合体


 

整理自:

http://www.cnblogs.com/lovewf/archive/2011/12/06/2277473.html

http://www.cnblogs.com/lovewf/archive/2012/03/20/2407389.html

http://www.cnblogs.com/lovewf/archive/2012/03/21/2407403.html

原创粉丝点击