欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > Android >内容正文

Android

Android自定义ViewGroup的OnMeasure和onLayout详解

发布时间:2025/3/20 Android 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Android自定义ViewGroup的OnMeasure和onLayout详解 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

前一篇文章主要讲了自定义View为什么要重载onMeasure()方法http://blog.csdn.net/tuke_tuke/article/details/73302595

那么,自定义ViewGroup又都有哪些方法需要重载或者实现呢 ?

Android开发中,对于自定义View,分为两种,一种是自定义控件(继承View类)。一种是自定义布局容器(继承ViewGroup类)。如果是自定义控件,则一般要重写两个方法,一个是onMeasure(),用来测量尺寸,本质是该控件的父控件来测量该控件的尺寸,并通过widthMeasureSpec和heightMeasureSpec传到onMeasure的两个参数里供新控件参考,另一个是onDraw(),用来绘制控件的UI。

而自定义布局容器,则一般要重写三个方法,一个是onMeasure,也是来测量尺寸,但是它有两个任务一定要完成,就是“测量所有子控件的尺寸”和“设置自己的尺寸”(设置自己的尺寸过程其实和上篇自定View的中onMeasure过程相同,因为ViewGroup也是继承view);一个是onLayout(),用来布局子控件;还有一个是dispatchDraw(),用来绘制UI。


onLayout(),用来布局子控件具体是什么意思呢?怎样来实现布局子控件的呢?

本文先分析一个自定义ViewGroup的例子,然后在分析View,ViewGroup的源码,LinearLayout,RelativeLayout的源码是怎样使用和实现onMeasure和onLayout的。


ViewGroup类的onLayout()函数是abstract类型,继承者必须实现。由于ViewGroup的定位是一个容器,用来盛放子控件的,所以就必须要以什么方式来盛放,比如LinearLayout就是以横向或者纵向顺序存放,而RelativeLayout则以相对位置来摆放子控件,同样,我们的自定义ViewGroup也必须给出我们期望的布局方式,而这个定义就通过onLayout()函数来实现。

我们通过实现一个水平优先布局的视图容器来更加深入地了解onLayout()的实现吧,

1. 自定义ViewGroup的派生类

第一步,则是自定ViewGroup的派生类,继承默认的构造函数。

/*** 作者:tuke on 2017/6/17 11:31* 邮箱:2297535832@qq.com*/ public class CustomViewGroup extends ViewGroup {public CustomViewGroup(Context context) {super(context);}public CustomViewGroup(Context context, AttributeSet attrs) {super(context, attrs);}public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);} 2. 重载onMeasure()方法
为什么要重载onMeasure()方法这里就不赘述了,上一篇文章已经讲过,这里需要注意的是,自定义ViewGroup的onMeasure()方法中,除了计算自身的尺寸外,还需要调用measureChildren()函数来计算子控件的尺寸。

onMeasure()的定义不是本文的讨论重点,因此这里我直接使用默认的onMeasure()定义,当然measureChildren()是必须得加的。

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//测量所有子控件的宽和高measureChildren(widthMeasureSpec,heightMeasureSpec);//调用系统的onMeasure一般是测量自己(当前ViewGroup)的宽和高super.onMeasure(widthMeasureSpec, heightMeasureSpec);}


          在ViewGroup类中只有抽象的onLayout函数,OnMeasure函数是在view中,因为ViewGroup继承了View所以这里的super.onMeasure就是系统默认的onMeasure(见上一篇文章)测量并设置此自定义ViewGroup的宽和高,因为layout文件中设置的是match_parent,所以就是全屏。当然如果对此自定义ViewGroup宽和高有要求,layout文件中设置的是wrap_content,就不使用super.onMeasure,而是根据所有子控件的宽高,计算出开发者需要的宽高,然后同样使用setMeasureDemension设置此自定义ViewGroup的宽高。

     

      小结一下:就是layout文件中如果是match_parent和固定值,就可以用系统的onMeasure,如果设置的是wrap_content,就需要重写onMeasure,根据需要计算出宽和高,用setMeasureDemension设置进去。对自定义View和自定义ViewGroup都适用。


3. 实现onLayout()方法

由于我们希望优先横向布局子控件,那么,首先,我们知道总宽度是多少,这个值可以通过getMeasuredWidth()来得到,当然子控件的宽度也可以通过子控件对象的getMeasuredWidth()来得到。


/*** @param changed 该参数支出当前ViewGroup的尺寸或者位置是否发生了改变* @param l,t,r,b 当前ViewGroup相对于父控件的坐标位置,注意 ,一定是相对于父控件。* 函数的参数l,t,r,b,也是由该VieGroup的父控件传过来的*/@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {int mViewGroupWidth=getMeasuredWidth(); //当前ViewGroup的总宽度int mPainterPosX=l;//当前绘制光标X坐标int mPainterPosY=t;//当前绘制光标Y坐标int childCount=getChildCount();//子控件的数量//遍历所有子控件,并在其位置上绘制子控件for (int i=0;i<childCount;i++){View childView=getChildAt(i);//子控件的宽和高int width=childView.getMeasuredWidth();int height=childView.getMeasuredHeight();//如果剩余控件不够,则移到下一行开始位置if(mPainterPosX+width>mViewGroupWidth){mPainterPosX=l;mPainterPosY+=height;}//执行childView的绘制childView.layout(mPainterPosX,mPainterPosY,mPainterPosX+width,mPainterPosY+height);//下一次绘制的X坐标mPainterPosX+=width;}}
4. 布局文件测试
下面我们就尝试写一个简单的xml文件,来测试一下我们的自定义ViewGroup,我们把子View的背景颜色都设置为黑色,方便我们辨识。

<?xml version="1.0" encoding="utf-8"?> <com.example.customviewgroup.CustomViewGroupxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#D6D6D6"><Viewandroid:layout_width="100dp"android:layout_height="100dp"android:layout_margin="10dp"android:background="#000000"/><Viewandroid:layout_width="100dp"android:layout_height="100dp"android:layout_margin="10dp"android:background="#000000"/><Viewandroid:layout_width="100dp"android:layout_height="100dp"android:layout_margin="10dp"android:background="#000000"/><Viewandroid:layout_width="100dp"android:layout_height="100dp"android:layout_margin="10dp"android:background="#000000"/></com.example.customviewgroup.CustomViewGroup> 结果



这时可能会疑惑,为什么View中的margin属性没有效果,所以子控件一个个紧挨着排列,中间没有空隙。那么,下面我们来研究下为什么没有效果?如何添加margin效果?

1,为什么没有效果?

其实一个ViewGroup要支持子控件的layout_margin参数,则自定义的ViewGroup类必须重写generateLayoutParams()函数,并且在该函数中返回一个ViewGroup.MarginLayoutParams派生类对象,也就是说还有定义一个静态内部类继承ViewGroup.MarginLayoutParams,这样布局才能使用mergin参数

说白了,1,定义一个内部类继承ViewGroup.MarginLayoutParams,2,重写generateLayoutParams()函数

ViewGroup.MarginLayoutParams的定义关键部分如下,它记录了子控件的layout_margin值:


你可以跟踪源码看看,其实XML文件中View的layout_xxx参数都是被传递到了各种自定义ViewGroup.LayoutParams派生类对象中,就是说自定义的ViewGroup或者LinearLayout等(都是ViewGroup的子类),要想使用期包含的子控件的layout_xxx参数,必须有一个静态内部类继承ViewGroup.LayoutParams,并在该内部类中进行扩展。

例如LinearLayout的LayoutParams定义的关键部分如下:

public static class LayoutParams extends ViewGroup.MarginLayoutParams {public float weight;public int gravity = -1;public LayoutParams(Context c, AttributeSet attrs) {super(c, attrs);TypedArray a = c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.LinearLayout_Layout);weight = a.getFloat(com.android.internal.R.styleable.LinearLayout_Layout_layout_weight, 0);gravity = a.getInt(com.android.internal.R.styleable.LinearLayout_Layout_layout_gravity, -1);a.recycle();}}@Overridepublic LayoutParams generateLayoutParams(AttributeSet attrs) {return new LinearLayout.LayoutParams(getContext(), attrs);} } 这样你大概就可以理解为什么LinearLayout的子控件支持weight和gravity的设置了吧,当然我们也可以这样自定义一些属于我们ViewGroup特有的params,这里就不详细讨论了,我们只继承MarginLayoutParams来获取子控件的margin值
//要使子控件的margin属性有效,必须定义静态内部类,继承ViewGroup.MarginLayoutParamspublic static class LayoutParams extends ViewGroup.MarginLayoutParams{public LayoutParams(Context c, AttributeSet attrs) {super(c, attrs);}}//要使子控件的margin属性有效,必须重写该函数,返回内部类实例@Overridepublic ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {return new CustomViewGroup.LayoutParams(getContext(),attrs);}
这样修改之后,我们就可以在onLayout()函数中获取子控件的layout_margin值了,添加了layout_margin的onLayout()函数实现如下所示:

@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {int mViewGroupWidth=getMeasuredWidth(); //当前ViewGroup的总宽度int mPainterPosX=l;//当前绘制光标X坐标int mPainterPosY=t;//当前绘制光标Y坐标int childCount=getChildCount();//子控件的数量//遍历所有子控件,并在其位置上绘制子控件for (int i=0;i<childCount;i++){View childView=getChildAt(i);//子控件的宽和高int width=childView.getMeasuredWidth();int height=childView.getMeasuredHeight();CustomViewGroup.LayoutParams params= (CustomViewGroup.LayoutParams) childView.getLayoutParams();//在onLayout中就可以获取子控件的mergin值了//ChildView占用的width = width+leftMargin+rightMargin//ChildView占用的height = height+topMargin+bottomMargin//如果剩余控件不够,则移到下一行开始位置if(mPainterPosX+width+params.leftMargin+params.rightMargin>mViewGroupWidth){mPainterPosX=l;mPainterPosY+=height+params.topMargin+params.bottomMargin;}//执行childView的绘制childView.layout(mPainterPosX+params.leftMargin,mPainterPosY+params.topMargin,mPainterPosX+width+params.leftMargin+params.rightMargin,mPainterPosY+height+params.topMargin+params.bottomMargin);//下一次绘制的X坐标mPainterPosX+=width+params.leftMargin+params.rightMargin;}}

整个代码: package com.example.customviewgroup;import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup;/*** 作者:tuke on 2017/6/17 11:31* 邮箱:2297535832@qq.com*/ public class CustomViewGroup extends ViewGroup {public CustomViewGroup(Context context) {super(context);}public CustomViewGroup(Context context, AttributeSet attrs) {super(context, attrs);}public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//测量所有子控件的宽和高,只有先测量了所有子控件的尺寸,后面才能使用child.getMeasuredWidth()measureChildren(widthMeasureSpec,heightMeasureSpec);//调用系统的onMeasure一般是测量自己(当前ViewGroup)的宽和高super.onMeasure(widthMeasureSpec, heightMeasureSpec);}/*** @param changed 该参数支出当前ViewGroup的尺寸或者位置是否发生了改变* @param l,t,r,b 当前ViewGroup相对于父控件的坐标位置,注意 ,一定是相对于父控件。* 函数的参数l,t,r,b,也是由该VieGroup的父控件传过来的*/@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {int mViewGroupWidth=getMeasuredWidth(); //当前ViewGroup的总宽度int mPainterPosX=l;//当前绘制光标X坐标int mPainterPosY=t;//当前绘制光标Y坐标int childCount=getChildCount();//子控件的数量//遍历所有子控件,并在其位置上绘制子控件for (int i=0;i<childCount;i++){View childView=getChildAt(i);//子控件的宽和高int width=childView.getMeasuredWidth();int height=childView.getMeasuredHeight();CustomViewGroup.LayoutParams params= (CustomViewGroup.LayoutParams) childView.getLayoutParams();//在onLayout中就可以获取子控件的mergin值了//ChildView占用的width = width+leftMargin+rightMargin//ChildView占用的height = height+topMargin+bottomMargin//如果剩余控件不够,则移到下一行开始位置if(mPainterPosX+width+params.leftMargin+params.rightMargin>mViewGroupWidth){mPainterPosX=l;mPainterPosY+=height+params.topMargin+params.bottomMargin;}//执行childView的绘制childView.layout(mPainterPosX+params.leftMargin,mPainterPosY+params.topMargin,mPainterPosX+width+params.leftMargin+params.rightMargin,mPainterPosY+height+params.topMargin+params.bottomMargin);//下一次绘制的X坐标mPainterPosX+=width+params.leftMargin+params.rightMargin;}}//要使子控件的margin属性有效,必须定义静态内部类,继承ViewGroup.MarginLayoutParamspublic static class LayoutParams extends ViewGroup.MarginLayoutParams{public LayoutParams(Context c, AttributeSet attrs) {super(c, attrs);}}//要使子控件的margin属性有效,必须重写该函数,返回内部类实例@Overridepublic ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {return new CustomViewGroup.LayoutParams(getContext(),attrs);} }

总结:说白了,onLayout函数主要是确定每个子控件的位置,并调用childview.layout()绘制。
二,ViewGroup的OnMeasure详解 通过上面的介绍,我们知道,如果要自定义ViewGroup就必须重写onMeasure方法,在这里完成两个任务,1,测量所有子控件的尺寸,2,设置自己的尺寸。
子控件的尺寸怎么测量呢?ViewGroup中提供了三个关于测量子控件的方法:
1,measureChildren方法 /***遍历ViewGroup中所有的子控件,调用measuireChild测量宽高*/protected void measureChildren (int widthMeasureSpec, int heightMeasureSpec) {final int size = mChildrenCount;final View[] children = mChildren;for (int i = 0; i < size; ++i) {final View child = children[i];if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {//测量某一个子控件宽高measureChild(child, widthMeasureSpec, heightMeasureSpec);}} }2,measureChild 方法 /** * 测量某一个child的宽高 */ protected void measureChild (View child, int parentWidthMeasureSpec,int parentHeightMeasureSpec) {final LayoutParams lp = child.getLayoutParams();//获取子控件的宽高约束规则final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight, lp. width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom, lp. height);child.measure(childWidthMeasureSpec, childHeightMeasureSpec); }
3,measureChildWithMargins 方法 /** * 测量某一个child的宽高,考虑margin值 */ protected void measureChildWithMargins (View child,int parentWidthMeasureSpec, int widthUsed,int parentHeightMeasureSpec, int heightUsed) {final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();//获取子控件的宽高约束规则final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight + lp. leftMargin + lp.rightMargin+ widthUsed, lp. width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom + lp. topMargin + lp.bottomMargin+ heightUsed, lp. height);//测量子控件child.measure(childWidthMeasureSpec, childHeightMeasureSpec); }三个方法分别做了那些工作大家应该比较清楚了吧?measureChildren 就是遍历所有子控件挨个测量,最终测量子控件的方法就是measureChild 和measureChildWithMargins 了

三,例子 在上面“2,重写onMeasure方法”小节中,直接使用的是super.onMeasure(见上一篇文章)测量并设置此自定ViewGroup的宽和高。如果我们将layout文件中此自定义ViewGroup的设置成wrap_content ,则需要重写onMeasure,根据子控件的大小尺寸来设置此自定义ViewGroup的尺寸。

 在ViewGroup类中只有抽象的onLayout函数,OnMeasure函数是在view中,因为ViewGroup继承了View所以这里的super.onMeasure就是系统默认的onMeasure(见上一篇文章)测量并设置此自定义ViewGroup的宽和高,因为layout文件中设置的是match_parent,所以就是全屏。当然如果对此自定义ViewGroup宽和高有要求,layout文件中设置的是wrap_content,就不使用super.onMeasure,而是根据所有子控件的宽高,计算出开发者需要的宽高,然后同样使用setMeasureDemension设置此自定义ViewGroup的宽高。

     

      小结一下:就是layout文件中如果是match_parent和固定值,就可以用系统的onMeasure,如果设置的是wrap_content,就需要重写onMeasure,根据需要计算出宽和高,用setMeasureDemension设置进去。对自定义View和自定义ViewGroup都适用。



下面的例子:待续。。。

总结

以上是生活随笔为你收集整理的Android自定义ViewGroup的OnMeasure和onLayout详解的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。