(安卓) 自定义ViewGroup (自定义ViewGroup的方式实现梯形布局)
上图:
ViewGroup的职责是啥?
ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性,都是为用于告诉容器的),我们的宽度(layout_width)、高度(layout_height)、对齐方式(layout_gravity)等;当然还有margin等;于是乎,ViewGroup的职能为:给childView计算出建议的宽和高和测量模式 ;决定childView的位置;为什么只是建议的宽和高,而不是直接确定呢,别忘了childView宽和高可以设置为wrap_content,这样只有childView才能计算出自己的宽和高。
上代码:
xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <bawe.day1102wangshang.MyViewGroup android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="150dp" android:layout_height="40dp" android:background="#f00" /> <TextView android:layout_width="150dp" android:layout_height="40dp" android:background="#02fac0" /> <TextView android:layout_width="150dp" android:layout_height="40dp" android:background="#0033ff" /> </bawe.day1102wangshang.MyViewGroup> </LinearLayout>
MyViewGroup类:
package bawe.day1102wangshang; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Created by 迷人的脚毛!! on 2017/11/2. */ 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 onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //测量子View的宽高,只有ViewFroup中有这个方法,直接继承自View是没有这个方法的 measureChildren(widthMeasureSpec,heightMeasureSpec); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { //拿到子控件的个数 int childCount = getChildCount(); //定义一个临时高度 int startHeight=0; int startWidth=0; //循环遍历出每一个View for(int a=0;a<childCount;a++){ View v = getChildAt(a); //给每一个view设置自己的位置 上 右 下 左 v.layout(startWidth,startHeight,startWidth+v.getMeasuredWidth(),startHeight+v.getMeasuredHeight()); startHeight+=v.getMeasuredHeight(); startWidth+=v.getMeasuredWidth(); } } }
不在 MainActivity中 写任何代码