自定义控件其实很简单8

通过上一节的讲解呢我们大致对Android测量控件有个初步的了解,而此后呢也有不少盆友Q小窗我问了不少问题,不过其实这些问题大多都不是问题,至于到底是不是问题呢,还要等我研究下究竟可不可以把这些问题归为问题……稍等、我吃个药先。大多数盆友的反应是在对控件测量的具体方法还不是很了解,不过不要着急,上一节的内容就当饭前甜点,接下来我们会用一个例子来说明这一切不是问题的问题,这个例子中的控件呢我称其为SquareLayout,意为方形布局(注:该例子仅作演示,实际应用意义并不大),我们将置于该布局下的所有子元素都强制变为一个正方形~~说起简单,但是如我上一节所说控件的设计要尽可能考虑到所有的可能性才能趋于完美~~但是没有绝对的完美……在5/12时我曾说过不要将自己当作一个coder而要把自己看成一个designer,控件是我们设计出来的而不是敲出来的,在我们code之前就该对这个控件有一个较为perfect的design,考虑到控件的属性设计、行为设计、交互设计等等,这里呢我也对我们的SquareLayout做了一个简单的设计:

非常简单,如上我们所说,SquareLayout内部的子元素都会以正方形的形状显示,我们可以给其定义一个orientation属性来表示子元素排列方式,如上是orientation为横向时的排列方式,而下面则是纵向的排列方式:

指定了排列方式后我们的子元素就会以此为基准排列下去,但是如果子元素超出了父容器的区域怎么办呢?这时我们可以指定两种处理方式:一、不管,任由子元素被父容器的边距裁剪;二、强制被裁剪的子元素舍弃其原有布局重新布局。暂时我们先默认第一种吧。接着看,如果我们的子元素只能是横着一排或竖着一排着实单调,我们可以考虑定义两个属性控制其最大排列个数,比如纵向排列时,我们可以指定一个max_row属性,当排列的行数超过该值时自动换列:

当然我们也可以在子元素横向排列时为其指定max_column属性,当横向排列列数超过该值时自动换行:

仔细想想,当max_column为1时,我们的排列方式其实就是纵向的而当max_row为1时就是横向的,那么我们的orientation属性岂不是成了摆设?会不会呢?留给各位去想。好吧、暂时就先定义这俩属性,光这俩已经够折腾的了,来来来创建我们的布局:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private int mMaxRow;// 最大行数

  9. private int mMaxColumn;// 最大列数

  10.  
  11. private int mOrientation;// 排列方向

  12.  
  13. public SquareLayout(Context context, AttributeSet attrs) {

  14. super(context, attrs);

  15. }

  16.  
  17. @Override

  18. protected void onLayout(boolean changed, int l, int t, int r, int b) {

  19. }

  20. }

上一节我们曾说过,要让我们父容器下子元素的margins外边距能够被正确计算,我们必需重写父容器的三个相关方法并返回一个MarginLayoutParams的子类:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去各种蛋疼的成员变量…………

  9.  
  10. // 省去构造方法…………

  11.  
  12. // 省去onLayout方法…………

  13.  
  14. @Override

  15. protected LayoutParams generateDefaultLayoutParams() {

  16. return new MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

  17. }

  18.  
  19. @Override

  20. protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {

  21. return new MarginLayoutParams(p);

  22. }

  23.  
  24. @Override

  25. public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {

  26. return new MarginLayoutParams(getContext(), attrs);

  27. }

  28. }

这里我直接返回一个MarginLayoutParams的实例对象,因为我不需要在LayoutParams处理自己的逻辑,单纯地计算margins就没必要去实现一个自定义的MarginLayoutParams子类了,除此之外,你还可以重写checkLayoutParams方法去验证当前所使用的LayoutParams对象是否MarginLayoutParams的一个实例:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去各种蛋疼的成员变量…………

  9.  
  10. // 省去构造方法…………

  11.  
  12. // 省去onLayout方法…………

  13.  
  14. // 省去三个屌毛方法……

  15.  
  16. @Override

  17. protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {

  18. return p instanceof MarginLayoutParams;

  19. }

  20. }

然后呢我们就要开始对控件进行测量了,首先重写onMeasure方法是肯定的,那么我们就先在onMeasure中先把测量的逻辑处理了先,不过我们还是按部就班一步一步来,先把排列方式搞定:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量标识值

  9. private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默认值

  10.  
  11. private int mMaxRow = DEFAULT_MAX_ROW;// 最大行数

  12. private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列数

  13.  
  14. private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默认横向

  15.  
  16. // 省去构造方法…………

  17.  
  18. @SuppressLint("NewApi")

  19. @Override

  20. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  21. /*

  22. * 声明临时变量存储父容器的期望值

  23. * 该值应该等于父容器的内边距加上所有子元素的测量宽高和外边距

  24. */

  25. int parentDesireWidth = 0;

  26. int parentDesireHeight = 0;

  27.  
  28. // 声明临时变量存储子元素的测量状态

  29. int childMeasureState = 0;

  30.  
  31. /*

  32. * 如果父容器内有子元素

  33. */

  34. if (getChildCount() > 0) {

  35. /*

  36. * 那么就遍历子元素

  37. */

  38. for (int i = 0; i < getChildCount(); i++) {

  39. // 获取对应遍历下标的子元素

  40. View child = getChildAt(i);

  41.  
  42. /*

  43. * 如果该子元素没有以“不占用空间”的方式隐藏则表示其需要被测量计算

  44. */

  45. if (child.getVisibility() != View.GONE) {

  46.  
  47. // 测量子元素并考量其外边距

  48. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

  49.  
  50. // 比较子元素测量宽高并比较取其较大值

  51. int childMeasureSize = Math.max(child.getMeasuredWidth(), child.getMeasuredHeight());

  52.  
  53. // 重新封装子元素测量规格

  54. int childMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasureSize, MeasureSpec.EXACTLY);

  55.  
  56. // 重新测量子元素

  57. child.measure(childMeasureSpec, childMeasureSpec);

  58.  
  59. // 获取子元素布局参数

  60. MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();

  61.  
  62. /*

  63. * 考量外边距计算子元素实际宽高

  64. */

  65. int childActualWidth = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;

  66. int childActualHeight = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;

  67.  
  68. /*

  69. * 如果为横向排列

  70. */

  71. if (mOrientation == ORIENTATION_HORIZONTAL) {

  72. // 累加子元素的实际宽度

  73. parentDesireWidth += childActualWidth;

  74.  
  75. // 获取子元素中高度最大值

  76. parentDesireHeight = Math.max(parentDesireHeight, childActualHeight);

  77. }

  78.  
  79. /*

  80. * 如果为竖向排列

  81. */

  82. else if (mOrientation == ORIENTATION_VERTICAL) {

  83. // 累加子元素的实际高度

  84. parentDesireHeight += childActualHeight;

  85.  
  86. // 获取子元素中宽度最大值

  87. parentDesireWidth = Math.max(parentDesireWidth, childActualWidth);

  88. }

  89.  
  90. // 合并子元素的测量状态

  91. childMeasureState = combineMeasuredStates(childMeasureState, child.getMeasuredState());

  92. }

  93. }

  94.  
  95. /*

  96. * 考量父容器内边距将其累加到期望值

  97. */

  98. parentDesireWidth += getPaddingLeft() + getPaddingRight();

  99. parentDesireHeight += getPaddingTop() + getPaddingBottom();

  100.  
  101. /*

  102. * 尝试比较父容器期望值与Android建议的最小值大小并取较大值

  103. */

  104. parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());

  105. parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());

  106. }

  107.  
  108. // 确定父容器的测量宽高

  109. setMeasuredDimension(resolveSizeAndState(parentDesireWidth, widthMeasureSpec, childMeasureState),

  110. resolveSizeAndState(parentDesireHeight, heightMeasureSpec, childMeasureState << MEASURED_HEIGHT_STATE_SHIFT));

  111. }

  112.  
  113. // 省去onLayout方法…………

  114.  
  115. // 省去四个屌毛方法……

  116. }

上面代码注释很清楚,具体的我就不扯了,小窗我的童鞋有一部分问过我上一节中我在确定测量尺寸时候使用的resolveSize方法作用(以下代码源自上一节的CustomLayout):

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/15

  5. *

  6. */

  7. public class CustomLayout extends ViewGroup {

  8. // 省去N多代码

  9.  
  10. @Override

  11. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  12. // 省省省………………

  13.  
  14. // 设置最终测量值

  15. setMeasuredDimension(resolveSize(parentDesireWidth, widthMeasureSpec), resolveSize(parentDesireHeight, heightMeasureSpec));

  16. }

  17.  
  18. // 省去N+1多代码

  19. }

那么这个resolveSize方法其实是View提供给我们解算尺寸大小的一个工具方法,其具体实现在API 11后交由另一个方法resolveSizeAndState也就是我们这一节例子所用到的去处理:

 
  1. public static int resolveSize(int size, int measureSpec) {

  2. return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;

  3. }

而这个resolveSizeAndState方法具体实现其实跟我们上一节开头解算Bitmap尺寸的逻辑类似:

 
  1. public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {

  2. int result = size;

  3. int specMode = MeasureSpec.getMode(measureSpec);

  4. int specSize = MeasureSpec.getSize(measureSpec);

  5. switch (specMode) {

  6. case MeasureSpec.UNSPECIFIED:

  7. result = size;

  8. break;

  9. case MeasureSpec.AT_MOST:

  10. if (specSize < size) {

  11. result = specSize | MEASURED_STATE_TOO_SMALL;

  12. } else {

  13. result = size;

  14. }

  15. break;

  16. case MeasureSpec.EXACTLY:

  17. result = specSize;

  18. break;

  19. }

  20. return result | (childMeasuredState&MEASURED_STATE_MASK);

  21. }

是不是很类似呢?如果没看过我上一节的内容,可以回头去阅读一下自定义控件其实很简单7/12,与我们不同的是这个方法多了一个childMeasuredState参数,而上面例子我们在具体测量时也引入了一个childMeasureState临时变量的计算,那么这个值的作用是什么呢?有何意义呢?说到这里不得不提API 11后引入的几个标识位:

这些标识位上面的代码中我们都有用到,而官方文档对其作用的说明也是模棱两可,源码里的运用也不明朗,比如说我们看其它几个与其相关的几个方法:

 
  1. public final int getMeasuredWidth() {

  2. return mMeasuredWidth & MEASURED_SIZE_MASK;

  3. }

  4. public final int getMeasuredHeight() {

  5. return mMeasuredHeight & MEASURED_SIZE_MASK;

  6. }

  7. public final int getMeasuredState() {

  8. return (mMeasuredWidth&MEASURED_STATE_MASK)

  9. | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)

  10. & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));

  11. }

这里大家注意getMeasuredWidth和getMeasuredHeight这两个我们用来获取控件测量宽高的方法,在其之中对其做了一个按位与的运算,然后才把这个测量值返回给我们,也就是说这个mMeasuredWidth和mMeasuredHeight里面应该还封装了些什么对吧,那么我们来看其赋值,其赋值是在setMeasuredDimension方法下进行的:

 
  1. protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {

  2. // 省去无关代码……

  3. mMeasuredWidth = measuredWidth;

  4. mMeasuredHeight = measuredHeight;

  5.  
  6. // 省去一行代码……

  7. }

也就是说当我们给控件设置最终测量尺寸时这个值就直接被赋予给了mMeasuredWidth和mMeasuredHeight这两个成员变量……看到这里很多朋友蛋疼了,那有啥区别和意义呢?我们尝试来翻翻系统自带控件关于它的处理,其中TextView没有涉及到这个参数的应用,而ImageView里则有:

 
  1. @Override

  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  3. // 省去海量代码…………

  4.  
  5. widthSize = resolveSizeAndState(w, widthMeasureSpec, 0);

  6. heightSize = resolveSizeAndState(h, heightMeasureSpec, 0);

  7.  
  8. // 省去一点代码…………

  9. }

在ImageView的onMeasure方法中使用resolveSizeAndState再次对计算得出的宽高进行解算,而这里的第三个参数直接传的0,也就是不作任何处理~~~~~~~~蛋疼!真蛋疼,以前寡人也曾纠结过一段时间,后来在stackoverflow在找到两个比较靠谱的答案:

大概意思就是当控件的测量尺寸比其父容器大时将会设置MEASURED_STATE_TOO_SMALL这个二进制值,而另一个stackoverflow的回答就更官方了:

注意右下角的用户名和头像,你就知道为什么这个回答有权威性了,鄙人是他脑残粉。来我们好好翻一下Romain这段话的意思:“childMeasuredState这个值呢由View.getMeasuredState()这个方法返回,一个布局(或者按我的说法父容器)通过View.combineMeasuredStates()这个方法来统计其子元素的测量状态。在大多数情况下你可以简单地只传递0作为参数值,而子元素状态值目前的作用只是用来告诉父容器在对其进行测量得出的测量值比它自身想要的尺寸要小,如果有必要的话一个对话框将会根据这个原因来重新校正它的尺寸。”So、可以看出,测量状态对谷歌官方而言也还算个测试性的功能,具体鄙人也没有找到很好的例证,如果大家谁找到了其具体的使用方法可以分享一下,这里我们还是就按照谷歌官方的建议依葫芦画瓢。好了这个问题就先到这里为止,我们继续看,在测量子元素尺寸时我分了两种情况:

 
  1. /*

  2. * 如果为横向排列

  3. */

  4. if (mOrientation == ORIENTATION_HORIZONTAL) {

  5. // 累加子元素的实际宽度

  6. parentDesireWidth += childActualWidth;

  7.  
  8. // 获取子元素中高度最大值

  9. parentDesireHeight = Math.max(parentDesireHeight, childActualHeight);

  10. }

  11.  
  12. /*

  13. * 如果为竖向排列

  14. */

  15. else if (mOrientation == ORIENTATION_VERTICAL) {

  16. // 累加子元素的实际高度

  17. parentDesireHeight += childActualHeight;

  18.  
  19. // 获取子元素中宽度最大值

  20. parentDesireWidth = Math.max(parentDesireWidth, childActualWidth);

  21. }

如果为横/竖向排列,那么我们应该统计各个子元素的宽/高,而高/宽呢则不需要统计,我们取其最高/最宽的那个子元素的值即可,注意在上一节的处理中我们并没有这样去做哦!不知道大家发现没~~~好了,onMeasure方法的逻辑就是这样,如果你觉得好长,那么恭喜你,这只是我们的第一步,尔后还有几个参数的处理~~~~~这时候你如果运行会发现什么都没有,因为onMeasure方法的作用仅仅是测量的一步,按照官方的说法,Android对Viewgroup的测量由两方面构成:一是对父容器和子元素大小尺寸的测量主要体现在onMeasure方法,二是对父容器的子元素在其区域内的定位主要体现在onLayout方法。也就是会说,即便我们完成了测量但没告诉儿子们该出现在哪的话也不会有任何显示效果,OK,现在我们来看看onLayout方法的逻辑处理:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量标识值

  9. private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默认值

  10.  
  11. private int mMaxRow = DEFAULT_MAX_ROW;// 最大行数

  12. private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列数

  13.  
  14. private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默认横向

  15.  
  16. // 省去构造方法…………

  17.  
  18. // 省去上面已经给过的onMeasure方法…………

  19.  
  20. @Override

  21. protected void onLayout(boolean changed, int l, int t, int r, int b) {

  22. /*

  23. * 如果父容器下有子元素

  24. */

  25. if (getChildCount() > 0) {

  26. // 声明临时变量存储宽高倍增值

  27. int multi = 0;

  28.  
  29. /*

  30. * 遍历子元素

  31. */

  32. for (int i = 0; i < getChildCount(); i++) {

  33. // 获取对应遍历下标的子元素

  34. View child = getChildAt(i);

  35.  
  36. /*

  37. * 如果该子元素没有以“不占用空间”的方式隐藏则表示其需要被测量计算

  38. */

  39. if (child.getVisibility() != View.GONE) {

  40. // 获取子元素布局参数

  41. MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();

  42.  
  43. // 获取控件尺寸

  44. int childActualSize = child.getMeasuredWidth();// child.getMeasuredHeight()

  45.  
  46. /*

  47. * 如果为横向排列

  48. */

  49. if (mOrientation == ORIENTATION_HORIZONTAL) {

  50. // 确定子元素左上、右下坐标

  51. child.layout(getPaddingLeft() + mlp.leftMargin + multi, getPaddingTop() + mlp.topMargin, childActualSize + getPaddingLeft()

  52. + mlp.leftMargin + multi, childActualSize + getPaddingTop() + mlp.topMargin);

  53.  
  54. // 累加倍增值

  55. multi += childActualSize + mlp.leftMargin + mlp.rightMargin;

  56. }

  57.  
  58. /*

  59. * 如果为竖向排列

  60. */

  61. else if (mOrientation == ORIENTATION_VERTICAL) {

  62. // 确定子元素左上、右下坐标

  63. child.layout(getPaddingLeft() + mlp.leftMargin, getPaddingTop() + mlp.topMargin + multi, childActualSize + getPaddingLeft()

  64. + mlp.leftMargin, childActualSize + getPaddingTop() + mlp.topMargin + multi);

  65.  
  66. // 累加倍增值

  67. multi += childActualSize + mlp.topMargin + mlp.bottomMargin;

  68. }

  69. }

  70. }

  71. }

  72. }

  73.  
  74. // 省去四个屌毛方法……

  75. }

比起对onMeasure方法的逻辑处理,onLayout方法相对简单,主要是在对子元素layout的地方需要我们一点计算思维,也不是很复杂,哥相信你能懂,毕竟注释如此清楚,来我们尝试用一下我们的布局:

 
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  2. android:layout_width="match_parent"

  3. android:layout_height="match_parent"

  4. android:layout_gravity="center"

  5. android:background="#ffffff" >

  6.  
  7. <com.aigestudio.customviewdemo.views.SquareLayout

  8. android:layout_width="match_parent"

  9. android:layout_height="wrap_content"

  10. android:paddingLeft="5dp"

  11. android:paddingTop="12dp"

  12. android:layout_margin="5dp"

  13. android:paddingRight="7dp"

  14. android:paddingBottom="20dp"

  15. android:layout_gravity="center"

  16. android:background="#679135" >

  17.  
  18. <Button

  19. android:layout_width="wrap_content"

  20. android:layout_height="wrap_content"

  21. android:background="#125793"

  22. android:text="tomorrow"

  23. android:textSize="24sp"

  24. android:textStyle="bold"

  25. android:typeface="serif" />

  26.  
  27. <Button

  28. android:layout_width="50dp"

  29. android:layout_height="100dp"

  30. android:layout_marginBottom="5dp"

  31. android:layout_marginLeft="10dp"

  32. android:layout_marginRight="20dp"

  33. android:layout_marginTop="30dp"

  34. android:background="#495287"

  35. android:text="AigeStudio" />

  36.  
  37. <ImageView

  38. android:layout_width="wrap_content"

  39. android:layout_height="wrap_content"

  40. android:layout_marginBottom="50dp"

  41. android:layout_marginLeft="5dp"

  42. android:layout_marginRight="20dp"

  43. android:layout_marginTop="15dp"

  44. android:background="#976234"

  45. android:scaleType="centerCrop"

  46. android:src="@drawable/lovestory_little" />

  47.  
  48. <Button

  49. android:layout_width="wrap_content"

  50. android:layout_height="wrap_content"

  51. android:background="#594342"

  52. android:text="AigeStudio" />

  53.  
  54. <Button

  55. android:layout_width="wrap_content"

  56. android:layout_height="wrap_content"

  57. android:background="#961315"

  58. android:text="AigeStudio" />

  59. </com.aigestudio.customviewdemo.views.SquareLayout>

  60.  
  61. </LinearLayout>

下面是运行后显示的效果:

将排列方式改为纵向排列:

private int mOrientation = ORIENTATION_VERTICAL;// 排列方向默认横向

再来瞅瞅ADT的显示效果:

在运行看看:

看样子目测还是很完美,不过这只是我们伟大的第一步而已!如我多次强调,控件的测量一定要尽可能地考虑到所有因素,这样你的控件才能立于N次不倒的暴力测试中,现在开始我们的第二步,max_row和max_column属性的计算:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量标识值

  9. private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默认值

  10.  
  11. private int mMaxRow = DEFAULT_MAX_ROW;// 最大行数

  12. private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列数

  13.  
  14. private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默认横向

  15.  
  16. public SquareLayout(Context context, AttributeSet attrs) {

  17. super(context, attrs);

  18.  
  19. // 初始化最大行列数

  20. mMaxRow = mMaxColumn = 2;

  21. }

  22.  
  23. // 省去onMeasure方法…………

  24.  
  25. // 省去onLayout方法…………

  26.  
  27. // 省去四个屌毛方法……

  28. }

首先呢在构造方法内初始化我们的最大行列数,不然我们可不可能造出Integer.MAX_VALUE这么多的子元素~~~~~

 
  1. // 初始化最大行列数

  2. mMaxRow = mMaxColumn = 2;

我们的SquareLayout中有5个子元素,那么这里就暂定我们的最大行列均为2好了,首先来看看onMeasure方法的逻辑处理,变动较大我先贴代码好了:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量标识值

  9. private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默认值

  10.  
  11. private int mMaxRow = DEFAULT_MAX_ROW;// 最大行数

  12. private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列数

  13.  
  14. private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默认横向

  15.  
  16. // 省去构造方法…………

  17.  
  18. @SuppressLint("NewApi")

  19. @Override

  20. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  21. /*

  22. * 声明临时变量存储父容器的期望值

  23. * 该值应该等于父容器的内边距加上所有子元素的测量宽高和外边距

  24. */

  25. int parentDesireWidth = 0;

  26. int parentDesireHeight = 0;

  27.  
  28. // 声明临时变量存储子元素的测量状态

  29. int childMeasureState = 0;

  30.  
  31. /*

  32. * 如果父容器内有子元素

  33. */

  34. if (getChildCount() > 0) {

  35. // 声明两个一维数组存储子元素宽高数据

  36. int[] childWidths = new int[getChildCount()];

  37. int[] childHeights = new int[getChildCount()];

  38.  
  39. /*

  40. * 那么就遍历子元素

  41. */

  42. for (int i = 0; i < getChildCount(); i++) {

  43. // 获取对应遍历下标的子元素

  44. View child = getChildAt(i);

  45.  
  46. /*

  47. * 如果该子元素没有以“不占用空间”的方式隐藏则表示其需要被测量计算

  48. */

  49. if (child.getVisibility() != View.GONE) {

  50.  
  51. // 测量子元素并考量其外边距

  52. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

  53.  
  54. // 比较子元素测量宽高并比较取其较大值

  55. int childMeasureSize = Math.max(child.getMeasuredWidth(), child.getMeasuredHeight());

  56.  
  57. // 重新封装子元素测量规格

  58. int childMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasureSize, MeasureSpec.EXACTLY);

  59.  
  60. // 重新测量子元素

  61. child.measure(childMeasureSpec, childMeasureSpec);

  62.  
  63. // 获取子元素布局参数

  64. MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();

  65.  
  66. /*

  67. * 考量外边距计算子元素实际宽高并将数据存入数组

  68. */

  69. childWidths[i] = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;

  70. childHeights[i] = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;

  71.  
  72. // 合并子元素的测量状态

  73. childMeasureState = combineMeasuredStates(childMeasureState, child.getMeasuredState());

  74. }

  75. }

  76.  
  77. // 声明临时变量存储行/列宽高

  78. int indexMultiWidth = 0, indexMultiHeight = 0;

  79.  
  80. /*

  81. * 如果为横向排列

  82. */

  83. if (mOrientation == ORIENTATION_HORIZONTAL) {

  84. /*

  85. * 如果子元素数量大于限定值则进行折行计算

  86. */

  87. if (getChildCount() > mMaxColumn) {

  88.  
  89. // 计算产生的行数

  90. int row = getChildCount() / mMaxColumn;

  91.  
  92. // 计算余数

  93. int remainder = getChildCount() % mMaxColumn;

  94.  
  95. // 声明临时变量存储子元素宽高数组下标值

  96. int index = 0;

  97.  
  98. /*

  99. * 遍历数组计算父容器期望宽高值

  100. */

  101. for (int x = 0; x < row; x++) {

  102. for (int y = 0; y < mMaxColumn; y++) {

  103. // 单行宽度累加

  104. indexMultiWidth += childWidths[index];

  105.  
  106. // 单行高度取最大值

  107. indexMultiHeight = Math.max(indexMultiHeight, childHeights[index++]);

  108. }

  109. // 每一行遍历完后将该行宽度与上一行宽度比较取最大值

  110. parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);

  111.  
  112. // 每一行遍历完后累加各行高度

  113. parentDesireHeight += indexMultiHeight;

  114.  
  115. // 重置参数

  116. indexMultiWidth = indexMultiHeight = 0;

  117. }

  118.  
  119. /*

  120. * 如果有余数表示有子元素未能占据一行

  121. */

  122. if (remainder != 0) {

  123. /*

  124. * 遍历剩下的这些子元素将其宽高计算到父容器期望值

  125. */

  126. for (int i = getChildCount() - remainder; i < getChildCount(); i++) {

  127. indexMultiWidth += childWidths[i];

  128. indexMultiHeight = Math.max(indexMultiHeight, childHeights[i]);

  129. }

  130. parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);

  131. parentDesireHeight += indexMultiHeight;

  132. indexMultiWidth = indexMultiHeight = 0;

  133. }

  134. }

  135.  
  136. /*

  137. * 如果子元素数量还没有限制值大那么直接计算即可不须折行

  138. */

  139. else {

  140. for (int i = 0; i < getChildCount(); i++) {

  141. // 累加子元素的实际高度

  142. parentDesireHeight += childHeights[i];

  143.  
  144. // 获取子元素中宽度最大值

  145. parentDesireWidth = Math.max(parentDesireWidth, childWidths[i]);

  146. }

  147. }

  148. }

  149.  
  150. /*

  151. * 如果为竖向排列

  152. */

  153. else if (mOrientation == ORIENTATION_VERTICAL) {

  154. if (getChildCount() > mMaxRow) {

  155. int column = getChildCount() / mMaxRow;

  156. int remainder = getChildCount() % mMaxRow;

  157. int index = 0;

  158.  
  159. for (int x = 0; x < column; x++) {

  160. for (int y = 0; y < mMaxRow; y++) {

  161. indexMultiHeight += childHeights[index];

  162. indexMultiWidth = Math.max(indexMultiWidth, childWidths[index++]);

  163. }

  164. parentDesireHeight = Math.max(parentDesireHeight, indexMultiHeight);

  165. parentDesireWidth += indexMultiWidth;

  166. indexMultiWidth = indexMultiHeight = 0;

  167. }

  168.  
  169. if (remainder != 0) {

  170. for (int i = getChildCount() - remainder; i < getChildCount(); i++) {

  171. indexMultiHeight += childHeights[i];

  172. indexMultiWidth = Math.max(indexMultiHeight, childWidths[i]);

  173. }

  174. parentDesireHeight = Math.max(parentDesireHeight, indexMultiHeight);

  175. parentDesireWidth += indexMultiWidth;

  176. indexMultiWidth = indexMultiHeight = 0;

  177. }

  178. } else {

  179. for (int i = 0; i < getChildCount(); i++) {

  180. // 累加子元素的实际宽度

  181. parentDesireWidth += childWidths[i];

  182.  
  183. // 获取子元素中高度最大值

  184. parentDesireHeight = Math.max(parentDesireHeight, childHeights[i]);

  185. }

  186. }

  187. }

  188.  
  189. /*

  190. * 考量父容器内边距将其累加到期望值

  191. */

  192. parentDesireWidth += getPaddingLeft() + getPaddingRight();

  193. parentDesireHeight += getPaddingTop() + getPaddingBottom();

  194.  
  195. /*

  196. * 尝试比较父容器期望值与Android建议的最小值大小并取较大值

  197. */

  198. parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());

  199. parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());

  200. }

  201.  
  202. // 确定父容器的测量宽高

  203. setMeasuredDimension(resolveSizeAndState(parentDesireWidth, widthMeasureSpec, childMeasureState),

  204. resolveSizeAndState(parentDesireHeight, heightMeasureSpec, childMeasureState << MEASURED_HEIGHT_STATE_SHIFT));

  205. }

  206.  
  207. // 省去onLayout方法…………

  208.  
  209. // 省去四个屌毛方法……

  210. }

逻辑计算变动较大,首先在遍历子元素时我没有直接对横纵向排列进行计算而是先用两个数组将子元素的宽高存储起来:

 
  1. @SuppressLint("NewApi")

  2. @Override

  3. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  4. // 省去几行代码…………

  5.  
  6. /*

  7. * 如果父容器内有子元素

  8. */

  9. if (getChildCount() > 0) {

  10. // 声明两个一维数组存储子元素宽高数据

  11. int[] childWidths = new int[getChildCount()];

  12. int[] childHeights = new int[getChildCount()];

  13.  
  14. /*

  15. * 那么就遍历子元素

  16. */

  17. for (int i = 0; i < getChildCount(); i++) {

  18. // 省省省……

  19.  
  20. /*

  21. * 如果该子元素没有以“不占用空间”的方式隐藏则表示其需要被测量计算

  22. */

  23. if (child.getVisibility() != View.GONE) {

  24.  
  25. // 省去N行代码……

  26.  
  27. /*

  28. * 考量外边距计算子元素实际宽高并将数据存入数组

  29. */

  30. childWidths[i] = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;

  31. childHeights[i] = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;

  32.  
  33. // 省去一行代码……

  34. }

  35. }

  36.  
  37. // 声明临时变量存储行/列宽高

  38. int indexMultiWidth = 0, indexMultiHeight = 0;

  39.  
  40. // 省去无数行代码……………………

  41. }

  42.  
  43. // 省去一行代码……

  44. }

然后上面还声明两个临时变量indexMultiWidth和indexMultiHeight用来分别存储单行/列的宽高并将该行计算后的结果累加到父容器的期望值,这里我们就看看横向排列的逻辑:

 
  1. /*

  2. * 如果为横向排列

  3. */

  4. if (mOrientation == ORIENTATION_HORIZONTAL) {

  5. /*

  6. * 如果子元素数量大于限定值则进行折行计算

  7. */

  8. if (getChildCount() > mMaxColumn) {

  9.  
  10. // 计算产生的行数

  11. int row = getChildCount() / mMaxColumn;

  12.  
  13. // 计算余数

  14. int remainder = getChildCount() % mMaxColumn;

  15.  
  16. // 声明临时变量存储子元素宽高数组下标值

  17. int index = 0;

  18.  
  19. /*

  20. * 遍历数组计算父容器期望宽高值

  21. */

  22. for (int x = 0; x < row; x++) {

  23. for (int y = 0; y < mMaxColumn; y++) {

  24. // 单行宽度累加

  25. indexMultiWidth += childWidths[index];

  26.  
  27. // 单行高度取最大值

  28. indexMultiHeight = Math.max(indexMultiHeight, childHeights[index++]);

  29. }

  30. // 每一行遍历完后将该行宽度与上一行宽度比较取最大值

  31. parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);

  32.  
  33. // 每一行遍历完后累加各行高度

  34. parentDesireHeight += indexMultiHeight;

  35.  
  36. // 重置参数

  37. indexMultiWidth = indexMultiHeight = 0;

  38. }

  39.  
  40. /*

  41. * 如果有余数表示有子元素未能占据一行

  42. */

  43. if (remainder != 0) {

  44. /*

  45. * 遍历剩下的这些子元素将其宽高计算到父容器期望值

  46. */

  47. for (int i = getChildCount() - remainder; i < getChildCount(); i++) {

  48. indexMultiWidth += childWidths[i];

  49. indexMultiHeight = Math.max(indexMultiHeight, childHeights[i]);

  50. }

  51. parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);

  52. parentDesireHeight += indexMultiHeight;

  53. indexMultiWidth = indexMultiHeight = 0;

  54. }

  55. }

  56.  
  57. /*

  58. * 如果子元素数量还没有限制值大那么直接计算即可不须折行

  59. */

  60. else {

  61. for (int i = 0; i < getChildCount(); i++) {

  62. // 累加子元素的实际高度

  63. parentDesireHeight += childHeights[i];

  64.  
  65. // 获取子元素中宽度最大值

  66. parentDesireWidth = Math.max(parentDesireWidth, childWidths[i]);

  67. }

  68. }

  69. }

计算我分了两种情况,子元素数量如果小于我们的限定值,例如我们布局下只有2个子元素,而我们的限定值为3,这时候就没必要计算折行,而另一种情况则是子元素数量大于我们的限定值,例如我们的布局下有7个子元素而我们的限定值为3,这时当我们横向排列到第三个子元素后就得折行了,在新的一行开始排列,在这种情况下,我们先计算了能被整除的子元素数:例如7/3为2余1,也就意味着我们此时能排满的只有两行,而多出来的那一行只有一个子元素,分别计算两种情况累加结果就OK了。纵向排列类似不说了,这里我逻辑比较臃肿,但是可以让大家很好理解,如果你Math好可以简化很多逻辑,不说了,既然onMeasure方法改动了,那么我们的onLayout方法也得跟上时代的步伐才行:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量标识值

  9. private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默认值

  10.  
  11. private int mMaxRow = DEFAULT_MAX_ROW;// 最大行数

  12. private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列数

  13.  
  14. private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默认横向

  15.  
  16. // 省去构造方法…………

  17.  
  18. // 省去上面已经给过的onMeasure方法…………

  19.  
  20. @Override

  21. protected void onLayout(boolean changed, int l, int t, int r, int b) {

  22. /*

  23. * 如果父容器下有子元素

  24. */

  25. if (getChildCount() > 0) {

  26. // 声明临时变量存储宽高倍增值

  27. int multi = 0;

  28.  
  29. // 指数倍增值

  30. int indexMulti = 1;

  31.  
  32. // 声明临时变量存储行/列宽高

  33. int indexMultiWidth = 0, indexMultiHeight = 0;

  34.  
  35. // 声明临时变量存储行/列临时宽高

  36. int tempHeight = 0, tempWidth = 0;

  37.  
  38. /*

  39. * 遍历子元素

  40. */

  41. for (int i = 0; i < getChildCount(); i++) {

  42. // 获取对应遍历下标的子元素

  43. View child = getChildAt(i);

  44.  
  45. /*

  46. * 如果该子元素没有以“不占用空间”的方式隐藏则表示其需要被测量计算

  47. */

  48. if (child.getVisibility() != View.GONE) {

  49. // 获取子元素布局参数

  50. MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();

  51.  
  52. // 获取控件尺寸

  53. int childActualSize = child.getMeasuredWidth();// child.getMeasuredHeight()

  54.  
  55. /*

  56. * 如果为横向排列

  57. */

  58. if (mOrientation == ORIENTATION_HORIZONTAL) {

  59. /*

  60. * 如果子元素数量比限定值大

  61. */

  62. if (getChildCount() > mMaxColumn) {

  63. /*

  64. * 根据当前子元素进行布局

  65. */

  66. if (i < mMaxColumn * indexMulti) {

  67. child.layout(getPaddingLeft() + mlp.leftMargin + indexMultiWidth, getPaddingTop() + mlp.topMargin + indexMultiHeight,

  68. childActualSize + getPaddingLeft() + mlp.leftMargin + indexMultiWidth, childActualSize + getPaddingTop()

  69. + mlp.topMargin + indexMultiHeight);

  70. indexMultiWidth += childActualSize + mlp.leftMargin + mlp.rightMargin;

  71. tempHeight = Math.max(tempHeight, childActualSize) + mlp.topMargin + mlp.bottomMargin;

  72.  
  73. /*

  74. * 如果下一次遍历到的子元素下标值大于限定值

  75. */

  76. if (i + 1 >= mMaxColumn * indexMulti) {

  77. // 那么累加高度到高度倍增值

  78. indexMultiHeight += tempHeight;

  79.  
  80. // 重置宽度倍增值

  81. indexMultiWidth = 0;

  82.  
  83. // 增加指数倍增值

  84. indexMulti++;

  85. }

  86. }

  87. } else {

  88. // 确定子元素左上、右下坐标

  89. child.layout(getPaddingLeft() + mlp.leftMargin + multi, getPaddingTop() + mlp.topMargin, childActualSize

  90. + getPaddingLeft() + mlp.leftMargin + multi, childActualSize + getPaddingTop() + mlp.topMargin);

  91.  
  92. // 累加倍增值

  93. multi += childActualSize + mlp.leftMargin + mlp.rightMargin;

  94. }

  95. }

  96.  
  97. /*

  98. * 如果为竖向排列

  99. */

  100. else if (mOrientation == ORIENTATION_VERTICAL) {

  101. if (getChildCount() > mMaxRow) {

  102. if (i < mMaxRow * indexMulti) {

  103. child.layout(getPaddingLeft() + mlp.leftMargin + indexMultiWidth, getPaddingTop() + mlp.topMargin + indexMultiHeight,

  104. childActualSize + getPaddingLeft() + mlp.leftMargin + indexMultiWidth, childActualSize + getPaddingTop()

  105. + mlp.topMargin + indexMultiHeight);

  106. indexMultiHeight += childActualSize + mlp.topMargin + mlp.bottomMargin;

  107. tempWidth = Math.max(tempWidth, childActualSize) + mlp.leftMargin + mlp.rightMargin;

  108. if (i + 1 >= mMaxRow * indexMulti) {

  109. indexMultiWidth += tempWidth;

  110. indexMultiHeight = 0;

  111. indexMulti++;

  112. }

  113. }

  114. } else {

  115. // 确定子元素左上、右下坐标

  116. child.layout(getPaddingLeft() + mlp.leftMargin, getPaddingTop() + mlp.topMargin + multi, childActualSize

  117. + getPaddingLeft() + mlp.leftMargin, childActualSize + getPaddingTop() + mlp.topMargin + multi);

  118.  
  119. // 累加倍增值

  120. multi += childActualSize + mlp.topMargin + mlp.bottomMargin;

  121. }

  122. }

  123. }

  124. }

  125. }

  126. }

  127.  
  128. // 省去四个屌毛方法……

  129. }

onLayout方法就不具体说了,其实现要比onMeasure方法简单,我们稍微更改下布局文件尽可能地测试多种情况:

 
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  2. android:layout_width="match_parent"

  3. android:layout_height="match_parent"

  4. android:layout_gravity="center"

  5. android:background="#ffffff" >

  6.  
  7. <com.aigestudio.customviewdemo.views.SquareLayout

  8. android:layout_width="wrap_content"

  9. android:layout_height="wrap_content"

  10. android:layout_gravity="center"

  11. android:layout_margin="5dp"

  12. android:background="#679135"

  13. android:paddingBottom="20dp"

  14. android:paddingLeft="5dp"

  15. android:paddingRight="7dp"

  16. android:paddingTop="12dp" >

  17.  
  18. <Button

  19. android:layout_width="wrap_content"

  20. android:layout_height="wrap_content"

  21. android:background="#125793"

  22. android:text="tomorrow"

  23. android:textSize="24sp"

  24. android:textStyle="bold"

  25. android:typeface="serif" />

  26.  
  27. <Button

  28. android:layout_width="50dp"

  29. android:layout_height="100dp"

  30. android:layout_marginBottom="5dp"

  31. android:layout_marginLeft="10dp"

  32. android:layout_marginRight="20dp"

  33. android:layout_marginTop="30dp"

  34. android:background="#495287"

  35. android:text="AigeStudio" />

  36.  
  37. <LinearLayout

  38. android:layout_width="wrap_content"

  39. android:layout_height="wrap_content"

  40. android:layout_marginBottom="50dp"

  41. android:layout_marginLeft="5dp"

  42. android:layout_marginRight="20dp"

  43. android:layout_marginTop="15dp"

  44. android:background="#976234" >

  45.  
  46. <ImageView

  47. android:layout_width="wrap_content"

  48. android:layout_height="wrap_content"

  49. android:scaleType="centerCrop"

  50. android:src="@drawable/lovestory_little" />

  51. </LinearLayout>

  52.  
  53. <Button

  54. android:layout_width="wrap_content"

  55. android:layout_height="wrap_content"

  56. android:background="#594342"

  57. android:text="AigeStudio" />

  58.  
  59. <Button

  60. android:layout_width="wrap_content"

  61. android:layout_height="wrap_content"

  62. android:background="#961315"

  63. android:text="Welcome AigeStudio" />

  64. </com.aigestudio.customviewdemo.views.SquareLayout>

  65.  
  66. </LinearLayout>

下面看看ADT中的直接显示效果:

运行后的显示效果:

换成纵向排列看看:

运行后的效果:

尝试更改下纵向排列时的限制值:

 
  1. // 初始化最大行列数

  2. mMaxRow = 2;

  3. mMaxColumn =3;

直接看运行效果:

表示暂时木有发现什么大问题,OK,这两个属性值的实现就到这里,虽然只有两个属性值  =  =   TMD实在是菊紧啊,可想而知LinearLayout等布局这么多属性控制是有多蛋疼了么,不过如我文章开头所说,我们的这个自定义布局实用意义不大,主要还是给大家演示了解下自定义布局是有多么蛋疼、啊不……是由多么复杂,像系统自带的那些布局控件都是经过N多update版本才有今天,即便如此,依然还有很多BUG,不过大多不会影响实际使用我们也可以很好地解决,所以,再次强调、控件的测量是一个极为严谨缜密的过程,稍有不慎你的控件便到处都会是说不出的BUG~~~~~上一节我们为了能让我们的自定义布局能对外边距进行计算,我们定义了一个内部类LayoutParams继承于MarginLayoutParams但是其中什么也没做,而这一节呢我们没有定义这么一个内部类而是直接返回MarginLayoutParams的实例,我们之所以能从布局参数中获取到外边距的属性值,比如:

 
  1. // 获取子元素布局参数

  2. MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();

然后各种

 
  1. mlp.leftMargin

  2. mlp.topMargin

  3. mlp.rightMargin

  4. mlp.bottomMargin

是因为在MarginLayoutParams中已经为我们定义好了这些参数,具体代码就不贴了,如果我们定义了自己的布局,我们也可以去定义自己的布局参数,比如我们在其中定义子元素在布局中的对其方式:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去无数代码…………

  9.  
  10. public static class LayoutParams extends MarginLayoutParams {

  11. public int mGravity;// 对齐方式

  12.  
  13. public LayoutParams(MarginLayoutParams source) {

  14. super(source);

  15. }

  16.  
  17. public LayoutParams(android.view.ViewGroup.LayoutParams source) {

  18. super(source);

  19. }

  20.  
  21. public LayoutParams(Context c, AttributeSet attrs) {

  22. super(c, attrs);

  23. }

  24.  
  25. public LayoutParams(int width, int height) {

  26. super(width, height);

  27. }

  28. }

  29. }

然后呢我们就要修改那四个屌毛方法返回我们自己定义的LayoutParams:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去无数代码…………

  9.  
  10. @Override

  11. protected LayoutParams generateDefaultLayoutParams() {

  12. return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

  13. }

  14.  
  15. @Override

  16. protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {

  17. return new LayoutParams(p);

  18. }

  19.  
  20. @Override

  21. public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {

  22. return new LayoutParams(getContext(), attrs);

  23. }

  24.  
  25. @Override

  26. protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {

  27. return p instanceof LayoutParams;

  28. }

  29.  
  30. // 省去LayoutParams的定义…………

  31. }

然后你就可以通过其获取这个对其方式的值:

 
  1. // 获取子元素布局参数

  2. LayoutParams mlp = (LayoutParams) child.getLayoutParams();

  3. if (mlp.mGravity == xxxxxxx) {

  4. ………………………………………………………………

  5. }

用法跟margin类似,那么我们如何为该变量赋值呢?方法多种多样,可以写死可以直接调用赋值,这里我们来看另外的一种方式:通过xml在布局文件中直接设置其属性值,我们在使用xml进行布局时经常会使用这样的方式指定属性值:

 
  1. android:layout_width="wrap_content"

  2. android:layout_height="wrap_content"

  3. android:background="#125793"

  4. android:text="tomorrow"

  5. android:textSize="24sp"

  6. android:textStyle="bold"

  7. android:typeface="serif"

使用起来灰常方便,而这里我们也可以自定义属于自己的xml属性,方法非常非常简单,首先需要我们在declare-styleable标签下定义我们的各类属性:

 
  1. <!-- http://blog.csdn.net/aigestudio -->

  2. <declare-styleable name="SquareLayout">

  3. <attr name="my_gravity" format="enum">

  4. <enum name="left" value="0" />

  5. <enum name="right" value="1" />

  6. <enum name="center" value="2" />

  7. <enum name="top" value="3" />

  8. <enum name="bottom" value="4" />

  9. </attr>

  10. </declare-styleable>

一般情况下,declare-styleable的定义存放在values/attr.xml文件中,属性定义好了我们就该在布局中使用这些属性,使用方法也很简单,比如我们在SquareLayout的Button中应用my_gravity属性:

 
  1. <Button

  2. xmlns:aigestudio="http://schemas.android.com/apk/res/com.aigestudio.customviewdemo"

  3. aigestudio:my_gravity="left" />

在使用自定义属性前声明我们包内的命名空间即可,你可以直接写在布局文件的根布局下,命名空间的声明有两种写法,上面是其一,其格式如下:

xmlns:你想要的名字="http://schemas.android.com/apk/res/完整包名"

第二种方式如果你是用的是Studio,IDE则会提示你使用该方式:

xmlns:你想要的名字="http://schemas.android.com/apk/res-auto"

都可以,最后就是从xml中获取这些属性了,我们可以直接简单地通过带有AttributeSet对象的构造方法来获取:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去无数代码…………

  9.  
  10. public static class LayoutParams extends MarginLayoutParams {

  11. public int mGravity;// 对齐方式

  12.  
  13. public LayoutParams(MarginLayoutParams source) {

  14. super(source);

  15. }

  16.  
  17. public LayoutParams(android.view.ViewGroup.LayoutParams source) {

  18. super(source);

  19. }

  20.  
  21. public LayoutParams(Context c, AttributeSet attrs) {

  22. super(c, attrs);

  23.  
  24. /*

  25. * 获取xml对应属性

  26. */

  27. TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.SquareLayout);

  28. mGravity = a.getInt(R.styleable.SquareLayout_my_gravity, 0);

  29. }

  30.  
  31. public LayoutParams(int width, int height) {

  32. super(width, height);

  33. }

  34. }

  35. }

通过Context的obtainStyledAttributes方法注入AttributeSet对象和我们资源文件中定义的declare-styleable属性获取一个TypedArray对象,我们通过这个TypedArray对象各种相应的方法来获取参数值,本来呢我之前写了很长的篇幅来给大家介绍这其中的过程,后来发现实在太繁琐太多干脆删了重写旨在教会大家如何用即可。Android支持如下十种不同类型的属性定义:

 
  1. <!-- http://blog.csdn.net/aigestudio -->

  2. <declare-styleable name="AttrView">

  3. <!-- 引用资源 -->

  4. <attr name="image" format="reference" />

  5. <!-- 颜色 -->

  6. <attr name="text_color" format="color" />

  7. <!-- 布尔值 -->

  8. <attr name="text_display" format="boolean" />

  9. <!-- 尺寸大小 -->

  10. <attr name="temp1" format="dimension" />

  11. <!-- 浮点值 -->

  12. <attr name="temp2" format="float" />

  13. <!-- 整型值 -->

  14. <attr name="temp3" format="integer" />

  15. <!-- 字符串 -->

  16. <attr name="text" format="string" />

  17. <!-- 百分比 -->

  18. <attr name="alpha" format="fraction" />

  19. <!-- 枚举 -->

  20. <attr name="text_align" format="integer">

  21. <enum name="left" value="0" />

  22. <enum name="right" value="1" />

  23. <enum name="center" value="2" />

  24. </attr>

  25. <!-- 位运算 -->

  26. <attr name="text_optimize" format="integer">

  27. <flag name="anti" value="0x001" />

  28. <flag name="dither" value="0x002" />

  29. <flag name="linear" value="0x004" />

  30. </attr>

  31. </declare-styleable>

name都是我乱取的不要在意,主要看后面的format,这些类型都很好理解,它们在TypedArray中都有各种对应或重载的方法,比如获取color的getColor方法,上面我们获取int的getInt等等,这里对大家来说比较新颖的是fraction百分比这个类型,其在TypedArray的对应方法如下:

getFraction(int index, int base, int pbase, float defValue)

第一个参数很好理解表示我们定义的属性资源ID,最后一个参数呢也和前面的getInt类似,主要是这第二、三个参数,其作用是分开来的,当我们在xml中使用百分比属性时有两种写法,一种是标准的10%而另一种是带p的10%p:

 
  1. aigestudio:alpha="10%"

  2. aigestudio:alpha="10%p"

当属性值为10%的时候base参数起作用,我们此时获取的参数值就等于(10% * base),而pbase参数则无效,同理当属性值为10%p时参数值就等于(10% * pbase)而base无效,Just it。还有两个比较类似的类型:枚举和位运算,这两个类型也很好理解,枚举嘛就是从众多的选项中选一个,而位运算则可以选多个并通过“|”组合各种结果:

aigestudio:text_optimize="anti|dither"

这种写法相信大家也很常见,比如layout_gravity属性就可以以类似的方式多选,这种方式有一个好处就是我们不用在属性声明中定义太多的值,上面的text_optimize属性只有三个对应值,但是在code中我们可以以位运算的方式组合这三个参数值:

 
  1. /*

  2. * 画笔优化的标识位们

  3. */

  4. private static final int OPTIMIZE_ANTI = 0x001, OPTIMIZE_DITHER = 0x002, OPTIMIZE_LINEAR = 0x004, OPTIMIZE_ANTI_DITHER = 0x003, OPTIMIZE_ANTI_LINEAR = 0x005, OPTIMIZE_DITHER_LINEAR = 0x006, OPTIMIZE_ALL = 0x007;

通过三个参数值的位运算我们实质上就得到了7种不同的结果,Just it。xml属性值的定义不难不多用几次就会就不多说了,上面呢我们通过自定义的属性mGravity来尝试定义子元素相对于父容器的对其方式,而事实上Android提供给我们一个简便的方法去计算这玩意,Android定义了Gravity类来实现我们对对其方式的计算,其中定义了大量的常量值定义不同对其方式,比如什么左对齐、右对齐、水平居中乱七八糟的等等,也提供了多个方法来实现计算,使用方式呢也不难,比如上面的布局参数我们换成如下方式:

 
  1. /**

  2. *

  3. * @author AigeStudio {@link http://blog.csdn.net/aigestudio}

  4. * @since 2015/1/23

  5. *

  6. */

  7. public class SquareLayout extends ViewGroup {

  8. // 省去无数代码…………

  9.  
  10. public static class LayoutParams extends MarginLayoutParams {

  11. public int mGravity = Gravity.LEFT | Gravity.RIGHT;// 对齐方式

  12.  
  13. // 省去没变的代码…………

  14. }

  15. }

而在我们的xml属性定义中则可以直接使用android:layout_gravity这样的name而无需定义类型值:

 
  1. <declare-styleable name="SquareLayout">

  2. <attr name="android:layout_gravity" />

  3. </declare-styleable>

这样则表示我们的属性使用的Android自带的标签,之后我们只需根据布局文件中layout_gravity属性的值调用Gravity类下的方法去计算对齐方式则可,Gravity类下的方法很好用,为什么这么说呢?因为其可以说是无关布局的,拿最简单的一个来说:

public static void apply(int gravity, int w, int h, Rect container, Rect outRect)

第一个参数表示我们的对其方式值,第二三个参数呢则表示我们要对齐的元素,这里通俗地说就是我们父容器下的子元素,而container参数表示的则是我们父容器的矩形区域,最后一个参数是接收计算后子元素位置区域的矩形对象,随便new个传进去就行,可见apply方式是根据矩形区域来计算对其方式的,所以说非常好用,我们只需在onLayout方法中确定出父容器的矩形区域就可以轻松地计算出子元素根据对其方式出现在父容器中的矩形区域,这一个过程留给大家自行尝试,我就不多说了,TMD说的太多,又忘了上一节的那个问题了、肏!!!!好吧,下一节再说那个问题,哦!对了,还有一个擦边球的东西忘了讲,在Android很多的布局控件中都会重写这么一个方法:

 
  1. @Override

  2. public boolean shouldDelayChildPressedState() {

  3. return false;

  4. }

并且都会一致地返回false,其作用是告诉framework我们当前的布局不是一个滚动的布局,我们这里的自定义布局控件也重写了该方法~~~好好了了,不讲了,这节就到此为止

猜你喜欢

转载自blog.csdn.net/suyimin2010/article/details/81734727