自定义view group 1

https://github.com/wanglianghai/CutomViewGroup1
注意:子view必须测量
1.创建
scroll view的子视图match_parent无效所以只有totalHeight没有heightSize
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //1.看需要给出大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
//插入1
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(totalWidth, totalHeight);
        } else if (widthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(totalWidth, totalHeight);
        } else if (heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSize, totalHeight);
        } else {
            setMeasuredDimension(widthSize, totalHeight);
        }

插入1//计算的里面的view的值

int totalWidth = 0, totalHeight = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View v = getChildAt(i);
            measureChild(v, widthMeasureSpec, heightMeasureSpec);//必须测量子view
            totalWidth = v.getMeasuredWidth();
            totalHeight += v.getMeasuredHeight();
        }
// 布局dp会改变比例值, 布局先加载在加载代码
    //view group布局的onLayout
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        l = 0;
        t = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View v = getChildAt(i);
            int preHeight = v.getMeasuredHeight();
            //layout :relative to parent
            if (l + v.getMeasuredWidth() > r) {
                l = 0;
            }
            v.layout(l, t, l += v.getMeasuredWidth(), t += preHeight);
        }
    }

2.使用
view group 中的 child view
image_item.xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/imageView"
           android:layout_width="100dp"
           android:layout_height="100dp"
           android:scaleType="fitXY"
           android:src="@mipmap/ic_launcher">
</ImageView>

activity中:实例化child view

ImageView image = (ImageView) LayoutInflater.from(this).inflate(R.layout.image_item, viewGroup, false);
CustomViewGroup viewGroup = (CustomViewGroup)findViewById(R.id.custom_view);//找到布局中的自定义视图

viewGroup.addView(image);//用add添加
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值