1 写一个类继承自ViewGroup
2 在onMeasure计算出ViewGroup占据的大小 也就是宽和高
3 接着在onLayout中在ViewGroup的宽高内一个一个摆放layout子View
下面看代码演示
package com.example.aaaa;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
public class MyLayoutextends ViewGroup {
/**
* 这是必须要重写的 两个函数的构造方法 否则报错 原因可以看源码
* 通过构造函数两个参数反射生成View的
*
* @param context
* @param attrs
*/
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
for (int i =0; i < count; i++) {
View v = getChildAt(i);
if (v.getVisibility() == View.VISIBLE) {
int childWidth = v.getMeasuredWidth();
int childHeight = v.getMeasuredHeight();
v.layout(l, t, l + childWidth, t + childHeight);
l += childWidth;
// t += childHeight; 这句放开可以竖向ViewGroup //28 29行同时放开实现梯子形ViewGroup
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measureWidth =0;
int measureHeight =0;
int count = getChildCount();
for (int i =0; i < count; i++) {
View v = getChildAt(i);
if (v.getVisibility() == View.VISIBLE) {
measureChild(v, widthMeasureSpec, heightMeasureSpec);
measureHeight = Math.max(measureHeight, v.getMeasuredHeight());
measureWidth += v.getMeasuredWidth();
// measureWidth = Math.max(measureWidth, v.getMeasuredWidth());
// measureHeight += v.getMeasuredHeight(); 放开实现竖向ViewGroup
// measureWidth += v.getMeasuredWidth();
// measureWidth += v.getMeasuredWidth(); 放开实现梯子形ViewGroup
}
}
measureWidth += getPaddingLeft() + getPaddingRight();
measureHeight += getPaddingTop() + getPaddingBottom();
setMeasuredDimension(measureWidth, measureHeight);
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
效果如下,梯子形ViewGroup
网友评论