<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.zhoukao1.MyViewGruop android:layout_width="500dp" android:layout_height="200dp" android:background="#ffffff"> <TextView android:layout_width="70dp" android:layout_height="40dp" android:background="#1af7d6" /> <TextView android:layout_width="70dp" android:layout_height="40dp" android:background="#2d3de8" /> <TextView android:layout_width="70dp" android:layout_height="40dp" android:background="#e80b30" /> <TextView android:layout_width="70dp" android:layout_height="40dp" android:background="#0a0607" /> <TextView android:layout_width="70dp" android:layout_height="40dp" android:background="#0be812" /> </com.example.zhoukao1.MyViewGruop> </LinearLayout>
package com.example.zhoukao111111; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Created by WYH on 2017/11/5. */ public class MyViewGroup extends ViewGroup { public MyViewGroup(Context context) { super(context); } public MyViewGroup(Context context, AttributeSet attrs) { super(context, attrs); } public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //测量子View的宽高,只有Viewgroup中有这个方法 直接继承View没有这个方法 measureChildren(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean b, int o, int i1, int i2, int i3) { //拿到子控件的个数 int childCount = getChildCount(); //定义一个临时变量 高度 int startHeight = 0; int startWidth = 0; //循环遍历每一个View for (int i = 0; i < childCount; i++) { View v = getChildAt(i); //给每一个View设置自己的位置 v.layout(startWidth, startHeight, startWidth+v.getMeasuredWidth(), startHeight + v.getMeasuredHeight()); startHeight += v.getMeasuredHeight(); startWidth +=v.getMeasuredWidth(); } } }