1 寫一個(gè)類繼承自ViewGroup
2 在onMeasure計(jì)算出ViewGroup占據(jù)的大小 也就是寬和高
3 接著在onLayout中在ViewGroup的寬高內(nèi)一個(gè)一個(gè)擺放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 {
/**
* 這是必須要重寫的 兩個(gè)函數(shù)的構(gòu)造方法 否則報(bào)錯(cuò) 原因可以看源碼
* 通過構(gòu)造函數(shù)兩個(gè)參數(shù)反射生成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行同時(shí)放開實(shí)現(xiàn)梯子形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();? 放開實(shí)現(xiàn)豎向ViewGroup
//? ? ? ? ? ? ? ? measureWidth += v.getMeasuredWidth();
//? ? ? ? ? ? ? ? measureWidth += v.getMeasuredWidth();? 放開實(shí)現(xiàn)梯子形ViewGroup
? ? ? ? ? ? }
}
measureWidth += getPaddingLeft() + getPaddingRight();
? ? ? ? measureHeight += getPaddingTop() + getPaddingBottom();
? ? ? ? setMeasuredDimension(measureWidth, measureHeight);
? ? ? ? // super.onMeasure(widthMeasureSpec, heightMeasureSpec);
? ? }
}
效果如下,梯子形ViewGroup