Android自定义控件ViewGroup

1.自定义ViewGroup第一步重写OnMeasure方法;

在onMeasure方法中一般情况下我们会利用父类传给我们的参数(int widthMeasureSpec, int heightMeasureSpec)来

获取Mode和Size:

        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

      之后可以调用int childCount = getChildCount();

      获取子元素数量

      for (int i = 0; i < childCount; i++) {

                            View child = getChildAt(i);

                            LayoutParams lp = child.getLayoutParams();

                            int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 0, lp.width);

                            int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, 0, lp.height);

                            child.measure(childWidthSpec, childHeightSpec);

                   }

     然后父元素的widthMode 和heightMode 计算自身的尺寸

    

     switch (widthMode) {

                   case MeasureSpec.EXACTLY:

     相当于父布局中match_parent,那么自身尺寸就可以等于widthSize

     而其他情况则需要根据自己的需求判断

     }

     switch (heightMode) {

     高度同理

     }

     最后一定要调用

     setMeasuredDimension(width, height);//保存自身

2.自定义ViewGroup第二步重写onLayout方法;

    其中方法的四个参数boolean changed, int l, int t, int r, int b是相对父容器的相对位置

    利用child.getMeasuredWidth()及child.getMeasuredHeight()获取大小就可以计算位置

    最后利用child.layout(left, top, right, bottom)方法摆放控件

    int childCount = getChildCount();

                   for (int i = 0; i < childCount; i++) {

                            View child = getChildAt(i)

                            child.getMeasuredWidth();

                            child.getMeasuredHeight();

                            child.layout(left, top, right, bottom)

                   }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值