android 在XML向ViewGroup中添加组件

在Android开发中,可以通过三种方式在XML布局中使用ViewGroup:1) 直接使用ViewGroup并手动添加子View;2) 在XML中配置ViewGroup及其子View;3) 混合布局,结合前两者。实现这一功能的关键在于ViewGroup的onMeasure和onLayout方法,分别用于遍历子元素和进行布局。通过参考链接可以了解更多详细信息。
摘要由CSDN通过智能技术生成

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

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 ++){
         Vie
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值