Android自定义ViewGroup入门

Android自定义ViewGroup入门

ViewGroup
ViewGroup是View的容器类,自定义ViewGroup就是继承ViewGroup,重写其中onMeasure()和onLayout()方法。

onMeasure()
onMeasure()这个方法中测量容器的大小,在这里你需要将自定义ViewGroup宽高测量出来,并且在setMeasuredDimension(width, height)方法中传入宽和高。
倘若你给定一个固定的宽高,那么在 onMeasure()中你只需要setMeasuredDimension(width, height)就行了。但是实际情况不可能这样所以需要用getChildAt(int)方法获取到子控件。

下面上代码

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        int height = 0
        int width = 0;
        //getChildCount()获取ViewGroup子控件个数,for循环遍历getChildAt()获取每一个子控件
        for (int i = 0; i < getChildCount(); i++) {
            height += getChildAt(i).getMeasuredHeight();//高度相加
            if (mp.width > width) {
                width = getChildAt(i).getMeasuredWidth();//宽度取最大的子控件宽度
            }
         }

        setMeasuredDimension(width, height);//设置ViewGroup的宽高
    }

到这里ViewGroup的宽高就设置好了,然后需要绘制每一个子View该怎么摆放。

onLayout()
在onLayout()绘制每一个子View,需要用到layout方法,四个参数分别为左、上、又、下,参数坐标基于ViewGroup的左上角(即左上角坐标为(0,0))

getChildAt(int i ).layout(int leftint top, int right, int bottom )

不多说直接上代码

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
       int height = 0;
       for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.layout(0, height, child.getMeasuredWidth(), child.getMeasuredHeight()+height);
            height 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值