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添加