1、概述

在写代码之前,我必须得问几个问题:

1、ViewGroup的职责是啥?

ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性,都是为用于告诉容器的),我们的宽度(layout_width)、高度(layout_height)、对齐方式(layout_gravity)等;当然还有margin等;于是乎,ViewGroup的职能为:给childView计算出建议的宽和高和测量模式 ;决定childView的位置;为什么只是建议的宽和高,而不是直接确定呢,别忘了childView宽和高可以设置为wrap_content,这样只有childView才能计算出自己的宽和高。

2、View的职责是啥?

View的职责,根据测量模式和ViewGroup给出的建议的宽和高,计算出自己的宽和高;同时还有个更重要的职责是:在ViewGroup为其指定的区域内绘制自己的形态。

3、ViewGroup和LayoutParams之间的关系?

大家可以回忆一下,当在LinearLayout中写childView的时候,可以写layout_gravity,layout_weight属性;在RelativeLayout中的childView有layout_centerInParent属性,却没有layout_gravity,layout_weight,这是为什么呢?这是因为每个ViewGroup需要指定一个LayoutParams,用于确定支持childView支持哪些属性,比如LinearLayout指定LinearLayout.LayoutParams等。如果大家去看LinearLayout的源码,会发现其内部定义了LinearLayout.LayoutParams,在此类中,你可以发现weight和gravity的身影。

2、View的3种测量模式

上面提到了ViewGroup会为childView指定测量模式,下面简单介绍下三种测量模式:

EXACTLY:表示设置了精确的值,一般当childView设置其宽、高为精确值、match_parent时,ViewGroup会将其设置为EXACTLY;

AT_MOST:表示子布局被限制在一个最大值内,一般当childView设置其宽、高为wrap_content时,ViewGroup会将其设置为AT_MOST;

UNSPECIFIED:表示子布局想要多大就多大,一般出现在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此种模式比较少见。

注:上面的每一行都有一个一般,意思上述不是绝对的,对于childView的mode的设置还会和ViewGroup的测量mode有一定的关系;当然了,这是第一篇自定义ViewGroup,而且绝大部分情况都是上面的规则,所以为了通俗易懂,暂不深入讨论其他内容。

3、从API角度进行浅析

上面叙述了ViewGroup和View的职责,下面从API角度进行浅析。

View的根据ViewGroup传人的测量值和模式,对自己宽高进行确定(onMeasure中完成),然后在onDraw中完成对自己的绘制。

ViewGroup需要给View传入view的测量值和模式(onMeasure中完成),而且对于此ViewGroup的父布局,自己也需要在onMeasure中完成对自己宽和高的确定。此外,需要在onLayout中完成对其childView的位置的指定。

4、完整的例子

需求:我们定义一个ViewGroup,内部可以传入0到4个childView,分别依次显示在左上角,右上角,左下角,右下角。

1、决定该ViewGroup的LayoutParams

对于我们这个例子,我们只需要ViewGroup能够支持margin即可,那么我们直接使用系统的MarginLayoutParams

  1. @Override
  2. public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
  3. {
  4. return new MarginLayoutParams(getContext(), attrs);
  5. }

重写父类的该方法,返回MarginLayoutParams的实例,这样就为我们的ViewGroup指定了其LayoutParams为MarginLayoutParams。

2、onMeasure

在onMeasure中计算childView的测量值以及模式,以及设置自己的宽和高:

  1. /**
  2. * 计算所有ChildView的宽度和高度 然后根据ChildView的计算结果,设置自己的宽和高
  3. */
  4. @Override
  5. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  6. {
  7. /**
  8. * 获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式
  9. */
  10. int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  11. int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  12. int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
  13. int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
  14. // 计算出所有的childView的宽和高
  15. measureChildren(widthMeasureSpec, heightMeasureSpec);
  16. /**
  17. * 记录如果是wrap_content是设置的宽和高
  18. */
  19. int width = 0;
  20. int height = 0;
  21. int cCount = getChildCount();
  22. int cWidth = 0;
  23. int cHeight = 0;
  24. MarginLayoutParams cParams = null;
  25. // 用于计算左边两个childView的高度
  26. int lHeight = 0;
  27. // 用于计算右边两个childView的高度,最终高度取二者之间大值
  28. int rHeight = 0;
  29. // 用于计算上边两个childView的宽度
  30. int tWidth = 0;
  31. // 用于计算下面两个childiew的宽度,最终宽度取二者之间大值
  32. int bWidth = 0;
  33. /**
  34. * 根据childView计算的出的宽和高,以及设置的margin计算容器的宽和高,主要用于容器是warp_content时
  35. */
  36. for (int i = 0; i < cCount; i++)
  37. {
  38. View childView = getChildAt(i);
  39. cWidth = childView.getMeasuredWidth();
  40. cHeight = childView.getMeasuredHeight();
  41. cParams = (MarginLayoutParams) childView.getLayoutParams();
  42. // 上面两个childView
  43. if (i == 0 || i == 1)
  44. {
  45. tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
  46. }
  47. if (i == 2 || i == 3)
  48. {
  49. bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
  50. }
  51. if (i == 0 || i == 2)
  52. {
  53. lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
  54. }
  55. if (i == 1 || i == 3)
  56. {
  57. rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
  58. }
  59. }
  60. width = Math.max(tWidth, bWidth);
  61. height = Math.max(lHeight, rHeight);
  62. /**
  63. * 如果是wrap_content设置为我们计算的值
  64. * 否则:直接设置为父容器计算的值
  65. */
  66. setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth
  67. : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight
  68. : height);
  69. }

10-14行,获取该ViewGroup父容器为其设置的计算模式和尺寸,大多情况下,只要不是wrap_content,父容器都能正确的计算其尺寸。所以我们自己需要计算如果设置为wrap_content时的宽和高,如何计算呢?那就是通过其childView的宽和高来进行计算。

17行,通过ViewGroup的measureChildren方法为其所有的孩子设置宽和高,此行执行完成后,childView的宽和高都已经正确的计算过了

43-71行,根据childView的宽和高,以及margin,计算ViewGroup在wrap_content时的宽和高。

80-82行,如果宽高属性值为wrap_content,则设置为43-71行中计算的值,否则为其父容器传入的宽和高。

3、onLayout对其所有childView进行定位(设置childView的绘制区域)

  1. // abstract method in viewgroup
  2. @Override
  3. protected void onLayout(boolean changed, int l, int t, int r, int b)
  4. {
  5. int cCount = getChildCount();
  6. int cWidth = 0;
  7. int cHeight = 0;
  8. MarginLayoutParams cParams = null;
  9. /**
  10. * 遍历所有childView根据其宽和高,以及margin进行布局
  11. */
  12. for (int i = 0; i < cCount; i++)
  13. {
  14. View childView = getChildAt(i);
  15. cWidth = childView.getMeasuredWidth();
  16. cHeight = childView.getMeasuredHeight();
  17. cParams = (MarginLayoutParams) childView.getLayoutParams();
  18. int cl = 0, ct = 0, cr = 0, cb = 0;
  19. switch (i)
  20. {
  21. case 0:
  22. cl = cParams.leftMargin;
  23. ct = cParams.topMargin;
  24. break;
  25. case 1:
  26. cl = getWidth() - cWidth - cParams.leftMargin
  27. - cParams.rightMargin;
  28. ct = cParams.topMargin;
  29. break;
  30. case 2:
  31. cl = cParams.leftMargin;
  32. ct = getHeight() - cHeight - cParams.bottomMargin;
  33. break;
  34. case 3:
  35. cl = getWidth() - cWidth - cParams.leftMargin
  36. - cParams.rightMargin;
  37. ct = getHeight() - cHeight - cParams.bottomMargin;
  38. break;
  39. }
  40. cr = cl + cWidth;
  41. cb = cHeight + ct;
  42. childView.layout(cl, ct, cr, cb);
  43. }
  44. }

代码比较容易懂:遍历所有的childView,根据childView的宽和高以及margin,然后分别将0,1,2,3位置的childView依次设置到左上、右上、左下、右下的位置。

如果是第一个View(index=0) :则childView.layout(cl, ct, cr, cb); cl为childView的leftMargin , ct 为topMargin , cr 为cl+ cWidth , cb为 ct + cHeight

如果是第二个View(index=1) :则childView.layout(cl, ct, cr, cb);

cl为getWidth() - cWidth - cParams.leftMargin- cParams.rightMargin;

ct 为topMargin , cr 为cl+ cWidth , cb为 ct + cHeight

剩下两个类似~

这样就完成了,我们的ViewGroup代码的编写,下面我们进行测试,分别设置宽高为固定值,wrap_content,match_parent

5、测试结果

布局1:

  1. <com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="200dp"
  4. android:layout_height="200dp"
  5. android:background="#AA333333" >
  6. <TextView
  7. android:layout_width="50dp"
  8. android:layout_height="50dp"
  9. android:background="#FF4444"
  10. android:gravity="center"
  11. android:text="0"
  12. android:textColor="#FFFFFF"
  13. android:textSize="22sp"
  14. android:textStyle="bold" />
  15. <TextView
  16. android:layout_width="50dp"
  17. android:layout_height="50dp"
  18. android:background="#00ff00"
  19. android:gravity="center"
  20. android:text="1"
  21. android:textColor="#FFFFFF"
  22. android:textSize="22sp"
  23. android:textStyle="bold" />
  24. <TextView
  25. android:layout_width="50dp"
  26. android:layout_height="50dp"
  27. android:background="#ff0000"
  28. android:gravity="center"
  29. android:text="2"
  30. android:textColor="#FFFFFF"
  31. android:textSize="22sp"
  32. android:textStyle="bold" />
  33. <TextView
  34. android:layout_width="50dp"
  35. android:layout_height="50dp"
  36. android:background="#0000ff"
  37. android:gravity="center"
  38. android:text="3"
  39. android:textColor="#FFFFFF"
  40. android:textSize="22sp"
  41. android:textStyle="bold" />
  42. </com.example.zhy_custom_viewgroup.CustomImgContainer>

ViewGroup宽和高设置为固定值

效果图:

布局2:

  1. <com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:background="#AA333333" >
  6. <TextView
  7. android:layout_width="150dp"
  8. android:layout_height="150dp"
  9. android:background="#E5ED05"
  10. android:gravity="center"
  11. android:text="0"
  12. android:textColor="#FFFFFF"
  13. android:textSize="22sp"
  14. android:textStyle="bold" />
  15. <TextView
  16. android:layout_width="50dp"
  17. android:layout_height="50dp"
  18. android:background="#00ff00"
  19. android:gravity="center"
  20. android:text="1"
  21. android:textColor="#FFFFFF"
  22. android:textSize="22sp"
  23. android:textStyle="bold" />
  24. <TextView
  25. android:layout_width="50dp"
  26. android:layout_height="50dp"
  27. android:background="#ff0000"
  28. android:gravity="center"
  29. android:text="2"
  30. android:textColor="#FFFFFF"
  31. android:textSize="22sp"
  32. android:textStyle="bold" />
  33. <TextView
  34. android:layout_width="50dp"
  35. android:layout_height="50dp"
  36. android:background="#0000ff"
  37. android:gravity="center"
  38. android:text="3"
  39. android:textColor="#FFFFFF"
  40. android:textSize="22sp"
  41. android:textStyle="bold" />
  42. </com.example.zhy_custom_viewgroup.CustomImgContainer>

ViewGroup的宽和高设置为wrap_content
效果图:

布局3:

  1. <com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#AA333333" >
  6. <TextView
  7. android:layout_width="150dp"
  8. android:layout_height="150dp"
  9. android:background="#E5ED05"
  10. android:gravity="center"
  11. android:text="0"
  12. android:textColor="#FFFFFF"
  13. android:textSize="22sp"
  14. android:textStyle="bold" />
  15. <TextView
  16. android:layout_width="50dp"
  17. android:layout_height="50dp"
  18. android:background="#00ff00"
  19. android:gravity="center"
  20. android:text="1"
  21. android:textColor="#FFFFFF"
  22. android:textSize="22sp"
  23. android:textStyle="bold" />
  24. <TextView
  25. android:layout_width="50dp"
  26. android:layout_height="50dp"
  27. android:background="#ff0000"
  28. android:gravity="center"
  29. android:text="2"
  30. android:textColor="#FFFFFF"
  31. android:textSize="22sp"
  32. android:textStyle="bold" />
  33. <TextView
  34. android:layout_width="150dp"
  35. android:layout_height="150dp"
  36. android:background="#0000ff"
  37. android:gravity="center"
  38. android:text="3"
  39. android:textColor="#FFFFFF"
  40. android:textSize="22sp"
  41. android:textStyle="bold" />
  42. </com.example.zhy_custom_viewgroup.CustomImgContainer>

ViewGroup的宽和高设置为match_parent

可以看到无论ViewGroup的宽和高的值如何定义,我们的需求都实现了预期的效果~~

好了,通过这篇教程,希望大家已经能够初步掌握自定义ViewGroup的步骤,大家可以尝试自定义ViewGroup去实现LinearLayout的效果~~

android 手把手教您自定义ViewGroup(一)的更多相关文章

  1. Android:手把手教你打造可缩放移动的ImageView(下)

    在上一篇Android:手把手教你打造可缩放移动的ImageView最后提出了一个注意点:当自定义的MatrixImageView如ViewPager.ListView等带有滑动效果的ViewGrou ...

  2. Android动画效果之自定义ViewGroup添加布局动画

    前言: 前面几篇文章介绍了补间动画.逐帧动画.属性动画,大部分都是针对View来实现的动画,那么该如何为了一个ViewGroup添加动画呢?今天结合自定义ViewGroup来学习一下布局动画.本文将通 ...

  3. Android ViewDragHelper完全解析 自定义ViewGroup神器

    Android ViewDragHelper完全解析 自定义ViewGroup神器   转载请标明出处: http://blog.csdn.net/lmj623565791/article/detai ...

  4. [Android Pro] Android开发实践:自定义ViewGroup的onLayout()分析

    reference to : http://www.linuxidc.com/Linux/2014-12/110165.htm 前一篇文章主要讲了自定义View为什么要重载onMeasure()方法( ...

  5. Android:手把手教你打造可缩放移动的ImageView(上)

    定义ImageView,实现功能如下: 1.初始化时图片垂直居中显示,拉伸图片宽度至ImageView宽度. 2.使用两根手指放大缩小图片,可设置最大放大倍数,当图片小于ImageView宽度时,在手 ...

  6. 手把手教你自定义attr

    最近在学习的过程中遇到了自定义的attr和自定义的style.因此各种百度,各种博客的学习,算是有了一个系统的了解.在这里记录下自己的收获. 一.为什么要使用自定义attr以及本文定位 在androi ...

  7. Android之自定义ViewGroup

    概述 在写代码之前,我必须得问几个问题: 1.ViewGroup的职责是啥? ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性, ...

  8. (转载)Android快速开发偷懒必备,一句话搞定所有ViewGroup的Adapter . 支持自定义ViewGroup

    [置顶] [Android]快速开发偷懒必备,一句话搞定所有ViewGroup的Adapter . 支持自定义ViewGroup 标签: androidAdapter快速开发0耦合 2016-12-1 ...

  9. Android 中的View与ViewGroup

    Android重点知识--View和ViewGroup与自定义控件 作者:丁明祥 邮箱:2780087178@qq.com 一.基础 ViewGroup 参考资料: Android 手把手教您自定义V ...

随机推荐

  1. shell脚本生成限定范围的随机数

    #!/bin/bash +)) 这串代码实现了随机生成从1~50之间是数 这串代码特别简单,就是利用RANDOM这个随机数生成器进行取余就能够实现,至于为什么取余时需要+1是因为在取余时如果被整除那么 ...

  2. CodeIgniter 3.0问题集锦

    1.由于ci 3.0的session采用文件存储,在配置好session存储的目录后,在使用时如果遇到如下session错误. 此处 fc 目录为我设置的session目录. 解决将fc目录权限设为7 ...

  3. bzoj1412最小割

    太羞耻了,m n写反了(主要是样例n m相等) 建图方法比较高(ji)端(chu),对于可以加栅栏的地方连上1的边,然后求最小割即可 为了让代码优(suo)美(duan),我写了一个check,避免多 ...

  4. 【生活没有希望】NOIP2010初赛 烽火传递 smartoj1475

    整天初赛题做做,生活没有希望 用单调队列优化的dp 因为满足后来的总比先来的(在某些方面)更优 所以能用单调队列 n2变成n #include <cstdio> ],b[],c[]; in ...

  5. 一篇笔记带你快速掌握面向对象的Javascript(纯手打)

    /** * 创建对象 */ //1.工厂模式 //特点: //创建的对象无法识别其对象类型,不支持instanceof等判断方法,无法标识不同的对象 function createObj(name,s ...

  6. C# 使用access,报错:标准表达式中数据类型不匹配

    最初以为是数字类型造成的,结果最后才发现是日期格式错误,这是我的参数 db.AddInParameter(dbCommand, "savedate", DbType.DateTim ...

  7. 使用 Graphviz 画拓扑图

    使用 Graphviz 画拓扑图 0)前述 本文着重讲一下 Graphviz 的风格控制,基础一些的就不在这里讲啦. graphviz 的主页是http://www.graphviz.org/. Gr ...

  8. java反射学习之一反射机制概述

    一.反射机制背景概述 1.反射(reflection)是java被视为动态语言的一个关键性质 2.反射机制指的是程序在运行时能获取任何类的内部所有信息 二.反射机制实现功能概述 1.只要给定类的全名, ...

  9. Servlet解决参数乱码问题

    为什么会产生乱码? 之所以会产生乱码,是由于服务器端和客户端的编码方式不一致造成的.客户端与服务器端的交互过程中,存在着两次数据交换:第一次,客户端向服务器端发起请求,第二次数据交换,服务器端响应客户 ...

  10. php+ajax..转

    php+ajax 登录注册页面 主要是登录注册功能,前端后台验证没有什么,这个大家可以自己加上去,比如过滤啊,正则啊等 还是先放图吧 这是登录及注册界面  点击注册切换到注册界面,点击登录切换到登录界 ...