《Android开发艺术探索》第4章 View的工作原理

r囧r小猫 2022-03-17 16:28 391阅读 0赞

本章代码GitHub地址:https://github.com/LittleFogCat/AndroidBookNote/tree/master/chapter04_view

4.0 要点

View的绘制流程
measure -> layout -> draw

常用回调
onAttach onVisibilityChanged onDetach

滑动处理

4.1 ViewRoot DecorView

首先是这张Android的窗口层级图
窗口层级
可以看到,在一个界面中,包含了一个Window,Window中包含了一个DecorView。DecorView其实是一个FrameLayout,一般包含了且仅包含一个竖直的LinearLayout,这个LinearLayout中又包含了一个TitleView和一个ContentView。我们调用setContentView(id)的时候,设置的就是这个ContentView的布局。

ViewRoot是WindowManager和DecorView之间的纽带。View的三大流程其实都是通过ViewRoot来完成的。
关于ViewRoot的来历,又是怎么成为WindowManager和DecorView的纽带的,书中只是一笔带过,这里来一探究竟。

4.1.*

顺着源码追踪,只看有用部分:

当ActivityThread收到一个Activity启动消息时,会调用handleLaunchActivity(ActivityClientRecord, Intent, String)方法,handleLaunchActivity方法中有以下几句:

  1. WindowManagerGlobal.initialize();
  2. Activity a = performLaunchActivity(r, customIntent);
  3. handleResumeActivity(r.token, false, r.isForward,
  4. !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

可以看到,handleLaunchActivity中调用了performLaunchActivityhandleResumeActivity两个方法。

performLaunchActivity()中,Activity被创建(onCreate也是在这里调用的),并且通过Activity.attach()方法将Window和Activity绑定。

  1. activity = mInstrumentation.newActivity(
  2. cl, component.getClassName(), r.intent);
  3. activity.attach(appContext, this, getInstrumentation(), r.token,
  4. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  5. r.embeddedID, r.lastNonConfigurationInstances, config,
  6. r.referrer, r.voiceInteractor, window, r.configCallback);

handleResumeActivity()方法中,DecorView会被添加到Window中。(同时这个方法里面也有一个performResumeActivity()方法,在这里调用Activity.onResume())。

最后,我们会调用Activity的makeVisible()方法,并通知AMS我们的Activity已经resume了。

  1. ViewManager wm = a.getWindowManager();
  2. // 将DecorView添加到Window中,但此时其是不可见的
  3. wm.addView(decor, l);
  4. // ==> mDecor.setVisibility(View.VISIBLE);
  5. r.activity.makeVisible();
  6. ActivityManager.getService().activityResumed(token);

继续跟踪wm.addView(View, ViewGroup.LayoutParams),会在WindowManagerGlobal这个单例类中找到:

  1. ViewRootImpl root;
  2. root = new ViewRootImpl(view.getContext(), display);
  3. root.setView(view, wparams, panelParentView);

这里的view即是decorView。至此,我们成功的建立起了WindowManager -> ViewRootImpl -> DecorView的关系。

4.2 MeasureSpec

4.2.1 MeasureSpec

网上讲MeasureSpec的有很多。简单的来讲,MeasureSpec就是这个View的大小(不准确,但是可以这样简化理解)。它是一个32位的整型,高2位代表SpecMode,低30位代表SpecSize。
SpecMode有三种:

  • UNSPECIFIED 父容器不对View做限制。
  • EXACTLY 精确测量模式,即View的最终大小。在View中设置具体数字大小,或者match_parent都是这个模式。
  • AT_MOST 可用大小模式,View的大小不会超过这个值。对应的是wrap_content。

4.2.2 MeasureSpec和LayoutParams的对应关系

我们在LayoutParams中会定义View的宽高,即布局xml中的android:layout_widthandroid:layout_height属性。一般来讲,我们会设置match_parentwrap_content或者具体的数值。
同时,我们会通过View的measure方法向其传递MeasureSpec。综合父布局的MeasureSpec和View的LayoutParam,我们可以计算出这个View的MeasureSpec。
抛开UNSPECIFIED不谈(一般不用),以下表格表示了如何通过二者确定View具体MeasureSpec的:


























LP \ 父SpecMode EXACTLY AT_MOST
具体数值 specMode: EXACTLY
specSize: View定义的size
specMode: EXACTLY
specSize: View定义的size
wrap_content specMode: AT_MOST
specSize: 父specSize
specMode: AT_MOST
specSize: 父specSize
match_parent specMode: EXACTLY
specSize: 父specSize
specMode: AT_MOST
specSize: 父specSize

可以看出,除非将View的宽高设定为确定的数值,否则其是受到父容器的影响的。具体的measure过程在下一节讲到。

4.3 View的工作流程

View的工作流程主要指measuer、layout、draw。
measure测量View的宽高,layout确定View的位置和大小,draw将View绘制在屏幕上。

4.3.1 measure

View通过measure来测量大小。同时,ViewGroup除了测量自己,还会遍历子View并调用其measure方法。
之前我们已经知道,View的大小由MeasureSpec来决定,而MeasureSpec又是通过父布局的MeasureSpec和LayoutParam共同决定的。
通过查看源码,我们可以看到,View的measure过程主要是通过在measure(int, int)方法中调用onMeasure(int, int)进行的。而onMeasure()的默认实现只有一句:

  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  2. setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
  3. getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
  4. }

我们在重写onMeasure方法的时候,必须要调用setMeasuredDimension(int measuredWidth, int measuredHeight)方法,否则系统会抛出异常。这个方法的主要目的是给View的mMeasuredWidthmMeasuredWidth变量赋值。
也就是说,measure的结果就是,通过调用measure(int, int)方法,最终给View的mMeasuredWidthmMeasuredWidth变量赋值,使得接下来的layout和draw流程顺利进行。
measure(int, int)方法的两个参数是从何而来的呢?
在4.2.2中我们知道了,View的MeasureSpec是通过父布局的MeasureSpec和自身的LayoutParam来进行计算的,而这个过程是在父ViewGroup中就已经完成了的,如4.2.2中表格所示。也就是说,事实上,measure过程绝大多数工作是在父容器里面就已经完成了的。
在ViewGroup类中有一个getChildMeasureSpec(int spec, int padding, int childDimension)方法,在这里我们可以看到ViewGroup是怎么确定子View的measureSpec的,截取其中一段:

  1. switch (specMode) {
  2. // Parent has imposed an exact size on us
  3. case MeasureSpec.EXACTLY:
  4. if (childDimension >= 0) {
  5. resultSize = childDimension;
  6. resultMode = MeasureSpec.EXACTLY;
  7. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  8. // Child wants to be our size. So be it.
  9. resultSize = size;
  10. resultMode = MeasureSpec.EXACTLY;
  11. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  12. // Child wants to determine its own size. It can't be
  13. // bigger than us.
  14. resultSize = size;
  15. resultMode = MeasureSpec.AT_MOST;
  16. }
  17. break;
  18. // Parent has imposed a maximum size on us
  19. case MeasureSpec.AT_MOST:
  20. if (childDimension >= 0) {
  21. // Child wants a specific size... so be it
  22. resultSize = childDimension;
  23. resultMode = MeasureSpec.EXACTLY;
  24. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  25. // Child wants to be our size, but our size is not fixed.
  26. // Constrain child to not be bigger than us.
  27. resultSize = size;
  28. resultMode = MeasureSpec.AT_MOST;
  29. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  30. // Child wants to determine its own size. It can't be
  31. // bigger than us.
  32. resultSize = size;
  33. resultMode = MeasureSpec.AT_MOST;
  34. }
  35. break;
  36. // Parent asked to see how big we want to be
  37. case MeasureSpec.UNSPECIFIED:
  38. if (childDimension >= 0) {
  39. // Child wants a specific size... let him have it
  40. resultSize = childDimension;
  41. resultMode = MeasureSpec.EXACTLY;
  42. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  43. // Child wants to be our size... find out how big it should
  44. // be
  45. resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
  46. resultMode = MeasureSpec.UNSPECIFIED;
  47. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  48. // Child wants to determine its own size.... find out how
  49. // big it should be
  50. resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
  51. resultMode = MeasureSpec.UNSPECIFIED;
  52. }
  53. break;
  54. }

特别地,当View的宽(或者高)设置为wrap_content的时候,查看4.2.2的表格,我们可以看到,View的SpecMode是AT_MOST,而SpecSize是父布局剩余的尺寸。也就是说,我们最后给这个View赋值的测量大小,也是父布局剩余尺寸,这跟match_parent是一样的效果,不符合我们的预期。造成这个结果的原因是,父布局并不知道这个View应该是多大,所以只能传递父布局的SpecSize。所以当我们自定义View的时候,需要重写onMeasure方法,并在其中加入当View的SpecMode是AT_MOST时,我们期望的测量结果。例如,我们想设置wrap_content时的宽高是100px:

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  4. int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
  5. int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
  6. int heightSpecMode = MeasureSpec.getMode(widthMeasureSpec);
  7. int heightSpecSize = MeasureSpec.getSize(widthMeasureSpec);
  8. if (widthSpecMode == MeasureSpec.AT_MOST && heightMeasureSpec == MeasureSpec.AT_MOST) {
  9. setMeasuredDimension(100, 100);
  10. } else if (widthSpecMode == MeasureSpec.AT_MOST) {
  11. setMeasuredDimension(100, heightSpecSize);
  12. } else if (heightSpecMode == MeasureSpec.AT_MOST) {
  13. setMeasuredDimension(widthSpecSize, 100);
  14. }
  15. }

而ViewGroup的measure过程,除了要测量自身以外,还要测量各个子View,测量完之后再计算出ViewGroup最终的大小。而这个过程根据ViewGroup的不同,最终测量出来的大小也可能是不一样的,例如LinearLayout和RelativeLayout,他们的测量过程显然不可能相同,所以ViewGroup并没有默认实现measure过程,在自定义ViewGroup的时候,必须重写onMeasure方法,否则会导致无法显示。虽然ViewGroup提供了measureChildren(int, int)和measureChild(View, int, int)方法,可以简便的对子元素进行测量,

4.3.2 layout

在计算好了尺寸之后,我们需要把View挨个放进ViewGroup里,如同搭积木一般。这个过程就是layout。所以我们可以简单的认为,layout的过程是为ViewGroup“量身定制”的。
layout过程跟measure很类似,ViewGroup遍历所有的子View,计算出其应在的位置。如同measure的最终结果是将mMeasuredWidthmMeasuredWidth变量赋值一般,layout的最终结果是给View的mLeft mTop mRight mBottom四个变量赋值。
在ViewGroup中,onLayout是一个抽象方法,需要我们自己实现,在其中放置我们的子View。举个简单的例子,我们要做个子元素竖直排列的布局,并且每个子元素间隔10px,重写ViewGroup的onLayout方法:

  1. @Override
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  3. int top = t;
  4. int count = getChildCount();
  5. for (int i = 0; i < count; i++) {
  6. final View child = getChildAt(i);
  7. int childLeft = l;
  8. int childTop = top;
  9. int childRight = childLeft + child.getMeasuredWidth();
  10. int childBottom = childTop + child.getMeasuredHeight();
  11. child.layout(childLeft, childTop, childRight, childBottom);
  12. top += child.getMeasuredHeight() + 10;
  13. }
  14. }

效果如下:
layout
可以看到符合预期。

4.3.3 draw

一般情况下,draw分为以下几步:

  1. 绘制背景(drawBackground)
  2. 绘制自身(onDraw)
  3. 绘制子元素(dispatchDraw)
  4. 绘制装饰(scrollbars)

我们一般只关心自身的绘制,也就是说,重写onDraw方法就可以了。对于自定义View的绘制,最重要的莫过于Canvas和Paint的使用。

4.3.4 小结*

View的三大流程,不是并列关系,而是依赖、递进的关系。也就是说,对于父布局,必须先测量好每个子元素的大小,再确定他们每个的位置,最后才能绘制出他们的图像。即:
measure -> layout -> draw

4.4 自定义View和ViewGroup

最后来根据本章内容做一下自定义View、ViewGroup。
预想图

我的目标是这样的:

  1. 自定义View:外圈圆形,包裹了一个五角星。可以自定义圆形和五角星的颜色,以及五角星的旋转角度。(其实旋转可以使用android:rotation属性的)
  2. 自定义ViewGroup:将所有的子View从左到右,从上到下,依次排列。

4.4.1 自定义View:StarView

4.4.1.0 定义属性

首先创建包含五角星各项数据的实体类Star

  1. public class Star {
  2. /** * 五角星从中心到顶点的距离 */
  3. private double mCVLength;
  4. /** * 中心点的坐标 */
  5. private Point mCenter;
  6. /** * 五角星旋转的角度 */
  7. private double mRotate;
  8. /** * 五角星5个顶点坐标,顺序为:从最上方顶点开始,顺时针旋转的所有顶点。 */
  9. private Point[] mPoints = new Point[5];
  10. // ...
  11. }

略去其他部分,这里主要保存了五角星从中心到顶点的距离(大小)、中心点的坐标(位置)、五角星旋转的角度(角度),以及五个顶点的坐标(前三个值计算得到)。而我们等下在绘制图形的过程中,主要用到的就是这五个点的坐标。(至于是怎么求到的,则是高中知识,过程充满了血泪不表)

现在开始自定义StarView。新建StarView.java,继承自View。在style.xml中加入如下属性:

  1. <declare-styleable name="StarView">
  2. <attr name="star_color" format="color" />
  3. <attr name="star_scale" format="float" />
  4. <attr name="star_rotate" format="float" />
  5. </declare-styleable>

分别代表五角星的颜色、五角星占圈内的比例、五角星的旋转角度。而圆圈背景则直接从background属性获取,然后再把背景设置成透明:

  1. Drawable bgDrawable = getBackground();
  2. if (bgDrawable instanceof ColorDrawable) {
  3. mBgColor = ((ColorDrawable) bgDrawable).getColor();
  4. } else {
  5. mBgColor = Color.RED;
  6. }
  7. setBackgroundColor(0);

是不是很粗暴?

4.4.1.1 onMeasure

在onMeasure中,我们只是处理了对于wrap_content的判断:如果长(宽)是wrap_content,那么就将其设置为与宽(长)相等,即正方形(实际绘图区域,即去掉了padding之后的真实绘图区域)。如果二者皆是wrap_content,那么就均设为默认大小。

4.4.1.2 onDraw

首先,我们去除了各种padding之后,得到了真实的圆心坐标(cx, cy)、半径r。半径的值为真实绘图区域短边的一半。然后调用canvas.drawCircle()方法绘制出背景圆形。
然后,我们定义的Star类就登场了。
回顾一下,我们创建了Star对象之后,就可以获取它的5个顶点坐标。知道了坐标,我们就可以通过Path + canvas.DrawPath()来绘图了。先使用Path对象,按我们平时手工的方法画一个五角星,然后再drawPath填充颜色。代码如下:

  1. // draw star
  2. Star star = getStar(mStarScale * r, cx, cy, mStarRotate);
  3. Star.Point points[] = star.getPoints();
  4. mPath.setFillType(Path.FillType.WINDING);
  5. mPath.moveTo(points[0].x, points[0].y);
  6. mPath.lineTo(points[3].x, points[3].y);
  7. mPath.lineTo(points[1].x, points[1].y);
  8. mPath.lineTo(points[4].x, points[4].y);
  9. mPath.lineTo(points[2].x, points[2].y);
  10. mPath.close();
  11. mPaint.setColor(mStarColor);
  12. canvas.drawPath(mPath, mPaint);

其中getStar()方法是为了避免在onDraw中创建对象。mPath.setFillType(Path.FillType.WINDING)允许我们完全填充这个路径内部。具体可以参考相关文章:https://blog.csdn.net/qq_30889373/article/details/78793086

4.4.1.3 完整代码

  1. /** * 圆形背景,五角星图案的自定义View。 */
  2. public class StarView extends View {
  3. private static final String TAG = "StarView";
  4. private static final int DEFAULT_SIZE_PX = 128;
  5. private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  6. private int mStarColor;
  7. private int mBgColor;
  8. private float mStarScale;
  9. private float mStarRotate;
  10. private Path mPath;
  11. public StarView(Context context) {
  12. this(context, null, 0);
  13. }
  14. public StarView(Context context, @Nullable AttributeSet attrs) {
  15. this(context, attrs, 0);
  16. }
  17. public StarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  18. super(context, attrs, defStyleAttr);
  19. TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StarView);
  20. mStarColor = a.getColor(R.styleable.StarView_star_color, Color.YELLOW);
  21. mStarScale = a.getFloat(R.styleable.StarView_star_scale, 0.8f);
  22. mStarRotate = a.getFloat(R.styleable.StarView_star_rotate, 0);
  23. a.recycle();
  24. init();
  25. }
  26. private void init() {
  27. Drawable bgDrawable = getBackground();
  28. if (bgDrawable instanceof ColorDrawable) {
  29. mBgColor = ((ColorDrawable) bgDrawable).getColor();
  30. } else {
  31. mBgColor = Color.RED;
  32. }
  33. setBackgroundColor(0);
  34. mPath = new Path();
  35. }
  36. @Override
  37. @SuppressWarnings("SuspiciousNameCombination")
  38. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  39. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  40. int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
  41. int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
  42. int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
  43. int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
  44. // 对长宽为wrap_content的判断
  45. if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
  46. setMeasuredDimension(DEFAULT_SIZE_PX, DEFAULT_SIZE_PX);
  47. } else if (widthSpecMode == MeasureSpec.AT_MOST) {
  48. int drawSize = heightSpecSize - getPaddingTop() - getPaddingBottom();
  49. setMeasuredDimension(drawSize + getPaddingLeft() + getPaddingRight(), heightSpecSize);
  50. } else if (heightSpecMode == MeasureSpec.AT_MOST) {
  51. int drawSize = widthSpecSize - getPaddingLeft() - getPaddingRight();
  52. setMeasuredDimension(widthSpecSize, drawSize + getPaddingTop() + getPaddingBottom());
  53. }
  54. }
  55. @Override
  56. protected void onDraw(Canvas canvas) {
  57. super.onDraw(canvas);
  58. int width = getWidth();
  59. int height = getHeight();
  60. int paddingLeft = getPaddingLeft();
  61. int paddingRight = getPaddingRight();
  62. int paddingTop = getPaddingTop();
  63. int paddingBottom = getPaddingBottom();
  64. int realWidth = width - paddingLeft - paddingRight;
  65. int realHeight = height - paddingTop - paddingBottom;
  66. if (realWidth <= 0 || realHeight <= 0) {
  67. return;
  68. }
  69. float cx, cy, r; // 圆心坐标x,圆心坐标y,半径
  70. r = Math.min(realWidth, realHeight) / 2.0f;
  71. cx = paddingLeft + r;
  72. cy = paddingTop + r;
  73. // draw background
  74. if (mBgColor != Color.TRANSPARENT) {
  75. mPaint.setColor(mBgColor);
  76. canvas.drawCircle(cx, cy, r, mPaint);
  77. }
  78. // draw star
  79. Star star = getStar(mStarScale * r, cx, cy, mStarRotate);
  80. Star.Point points[] = star.getPoints();
  81. mPath.setFillType(Path.FillType.WINDING);
  82. mPath.moveTo(points[0].x, points[0].y);
  83. mPath.lineTo(points[3].x, points[3].y);
  84. mPath.lineTo(points[1].x, points[1].y);
  85. mPath.lineTo(points[4].x, points[4].y);
  86. mPath.lineTo(points[2].x, points[2].y);
  87. mPath.close();
  88. mPaint.setColor(mStarColor);
  89. canvas.drawPath(mPath, mPaint);
  90. }
  91. /** * 由于onDraw中最好不要频繁的创建对象,所以使用临时的成员来保存Star。 */
  92. private Star mStarTemp;
  93. private Star getStar(double a, double cx, double cy, double rotate) {
  94. if (mStarTemp == null) {
  95. mStarTemp = new Star(a, cx, cy, rotate);
  96. } else {
  97. mStarTemp.setStar(a, cx, cy, rotate);
  98. }
  99. return mStarTemp;
  100. }
  101. }
  102. /** * 通过输入五角星的中心点坐标和顶点到中心的长度,计算出五角星每个顶点的坐标。 * <p> * Created by LittleFogCat on 2019/1/26. */
  103. @SuppressWarnings("WeakerAccess")
  104. public class Star {
  105. /** * 一些计算中常用的常数 */
  106. private static final double sin18 = sin(18);
  107. private static final double sin36 = sin(36);
  108. private static final double cos18 = cos(18);
  109. private static final double cos36 = cos(36);
  110. /** * 五角星从中心到顶点的距离 */
  111. private double mCVLength;
  112. /** * 中心点的坐标 */
  113. private Point mCenter;
  114. /** * 五角星旋转的角度 */
  115. private double mRotate;
  116. /** * 五角星5个顶点坐标,顺序为:从最上方顶点开始,顺时针旋转的所有顶点。 */
  117. private Point[] mPoints = new Point[5];
  118. /** * 构造函数,构造出一个正置无旋转的五角星。 * * @param a 五角星中心到顶点的距离 * @param cx 五角星中心坐标x * @param cy 五角星中心坐标y */
  119. public Star(double a, double cx, double cy) {
  120. this(a, cx, cy, 0);
  121. }
  122. /** * 主要构造函数。根据五角星中心坐标和中心到顶点的距离,计算出每个顶点的长度。 * * @param a 五角星中心到顶点的距离 * @param cx 五角星中心坐标x * @param cy 五角星中心坐标y * @param rotate 五角星旋转角度,0度为正置五角星 */
  123. public Star(double a, double cx, double cy, double rotate) {
  124. mCVLength = a;
  125. mCenter = new Point(cx, cy);
  126. mRotate = rotate;
  127. makeCoordinate();
  128. }
  129. public void setStar(double a, double cx, double cy, double rotate) {
  130. mCVLength = a;
  131. mCenter.x = (float) cx;
  132. mCenter.y = (float) cy;
  133. mRotate = rotate;
  134. makeCoordinate();
  135. }
  136. /** * 计算顶点坐标。 */
  137. private void makeCoordinate() {
  138. Point p[] = getPoints();
  139. final double x = mCenter.x;
  140. final double y = mCenter.y;
  141. final double a = mCVLength;
  142. if (mRotate == 0) {
  143. p[0] = new Point(x, y - a);
  144. p[1] = new Point(x + a * cos18, y - a * sin18);
  145. p[2] = new Point(x + a * sin36, y + a * cos36);
  146. p[3] = new Point(x - a * sin36, y + a * cos36);
  147. p[4] = new Point(x - a * cos18, y - a * sin18);
  148. } else {
  149. final double r = mRotate;
  150. for (int i = 0; i < 5; i++) {
  151. p[i] = new Point(x + a * sin(r + 72 * i), y - a * cos(r + 72 * i));
  152. }
  153. }
  154. }
  155. /** * 获取五角星的顶点坐标 * * @return 五角星的顶点坐标 */
  156. public Point[] getPoints() {
  157. if (mPoints == null || mPoints.length != 5) {
  158. mPoints = new Point[5];
  159. }
  160. return mPoints;
  161. }
  162. /** * {@link Math#sin(double)} 参数是弧度,这里转换为以度数为参数的函数 * * @param a degree * @return sin(a) */
  163. private static double sin(double a) {
  164. return Math.sin(Math.toRadians(a));
  165. }
  166. /** * {@link Math#cos(double)} 参数是弧度,这里转换为以度数为参数的函数 * * @param a degree * @return cos(a) */
  167. private static double cos(double a) {
  168. return Math.cos(Math.toRadians(a));
  169. }
  170. public static class Point {
  171. public float x, y;
  172. public Point() {
  173. }
  174. public Point(float x, float y) {
  175. this.x = x;
  176. this.y = y;
  177. }
  178. public Point(double x, double y) {
  179. this.x = (float) x;
  180. this.y = (float) y;
  181. }
  182. }
  183. }

4.4.2 自定义ViewGroup:FlowLayout

我们给他取了一个很好听的名字,FlowLayout流布局。实际上就是把子View挨个放。虽然写的时候感觉挺麻烦的,但是其实思路上面很简单,没什么复杂的地方。

4.4.2.0 onMeasure

只需要处理长(宽)是wrap_content的情况。思路很简单,挨个取出所有的子View:

  1. 如果宽是wrap_content,那么用变量保存最长行的宽度,本行宽度和本行剩余宽度;如果本行剩余宽度比这个子View小,那么就到下一行继续排,比较本行宽度和最长宽度;最后哪一行的宽度最宽,setMeasuredDimension的width就是它了(当然,不能超过parent的宽度);
  2. 如果高是wrap_content,那么和1中相同的排法,不同的就是记录每行最高的View高度,然后把他们全加起来,得到的就是总的高度了(当然,不能超过parent的高度);
  3. 如果宽高都是wrap_content,那么就是1和2的结合。

4.4.2.1 onLayout

排布方式已经在onMeasure中说过了,所以onLayout只需要简单的算一下子View的上下左右坐标即可。
需要注意的是,为了支持margin属性,我们需要自定义LayoutParams,继承自ViewGroup.MarginLayoutParams,然后重写generateLayoutParams()方法。

4.4.2.2 完整代码

  1. public class FlowLayout extends ViewGroup {
  2. public FlowLayout(Context context) {
  3. super(context);
  4. init();
  5. }
  6. public FlowLayout(Context context, AttributeSet attrs) {
  7. super(context, attrs);
  8. init();
  9. }
  10. public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
  11. super(context, attrs, defStyleAttr);
  12. init();
  13. }
  14. private void init() {
  15. }
  16. @Override
  17. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  18. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  19. int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  20. int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  21. int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  22. int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  23. final int childCount = getChildCount();
  24. measureChildrenWithMargins(widthMeasureSpec, heightMeasureSpec);
  25. if (childCount == 0) {
  26. setMeasuredDimension(0, 0);
  27. } else if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
  28. int totalWidth = getPaddingLeft() + getPaddingRight();
  29. int totalHeight = getPaddingTop() + getPaddingBottom();
  30. int rowWidth = getPaddingLeft() + getPaddingRight();
  31. int rowHeight = 0;
  32. for (int i = 0; i < childCount; i++) {
  33. View child = getChildAt(i);
  34. int childWidth = child.getMeasuredWidth();
  35. int childHeight = child.getMeasuredHeight();
  36. if (widthSize - rowWidth < childWidth) { // 行剩余空间不足,需要换行
  37. totalHeight += childHeight;
  38. rowHeight = childHeight;
  39. rowWidth = childWidth + getPaddingLeft() + getPaddingRight();
  40. } else {
  41. rowWidth += childWidth;
  42. if (childHeight > rowHeight) {
  43. rowHeight = childHeight;
  44. totalHeight += childHeight - rowHeight;
  45. }
  46. }
  47. if (totalWidth < rowWidth) {
  48. totalWidth = rowWidth;
  49. }
  50. }
  51. setMeasuredDimension(totalWidth, totalHeight);
  52. } else if (widthMode == MeasureSpec.AT_MOST) {
  53. int totalWidth = getPaddingLeft() + getPaddingRight();
  54. int rowWidth = getPaddingLeft() + getPaddingRight();
  55. int rowHeight = getPaddingTop() + getPaddingBottom();
  56. for (int i = 0; i < childCount; i++) {
  57. View child = getChildAt(i);
  58. int childWidth = child.getMeasuredWidth();
  59. int childHeight = child.getMeasuredHeight();
  60. if (widthSize - rowWidth < childWidth) { // 行剩余空间不足,需要换行
  61. rowHeight = childHeight;
  62. rowWidth = childWidth + getPaddingLeft() + getPaddingRight();
  63. } else {
  64. rowWidth += childWidth;
  65. if (childHeight > rowHeight) {
  66. rowHeight = childHeight;
  67. }
  68. }
  69. if (totalWidth < rowWidth) {
  70. totalWidth = rowWidth;
  71. }
  72. }
  73. setMeasuredDimension(totalWidth, heightSize);
  74. } else if (heightMode == MeasureSpec.AT_MOST) {
  75. int totalHeight = getPaddingTop() + getPaddingBottom();
  76. int rowWidth = getPaddingLeft() + getPaddingRight();
  77. int rowHeight = 0;
  78. for (int i = 0; i < childCount; i++) {
  79. View child = getChildAt(i);
  80. int childWidth = child.getMeasuredWidth();
  81. int childHeight = child.getMeasuredHeight();
  82. if (widthSize - rowWidth < childWidth) { // 行剩余空间不足,需要换行
  83. totalHeight += childHeight;
  84. rowHeight = childHeight;
  85. rowWidth = childWidth + getPaddingLeft() + getPaddingRight();
  86. } else {
  87. rowWidth += childWidth;
  88. if (childHeight > rowHeight) {
  89. rowHeight = childHeight;
  90. totalHeight += childHeight - rowHeight;
  91. }
  92. }
  93. }
  94. setMeasuredDimension(widthSize, totalHeight);
  95. }
  96. }
  97. protected void measureChildrenWithMargins(int widthMeasureSpec, int heightMeasureSpec) {
  98. int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
  99. int childCount = getChildCount();
  100. int widthUsed = getPaddingLeft() + getPaddingRight();
  101. int heightUsed = getPaddingTop() + getPaddingBottom();
  102. int rowHeight = 0;
  103. for (int i = 0; i < childCount; i++) {
  104. View child = getChildAt(i);
  105. LayoutParams lp = (LayoutParams) child.getLayoutParams();
  106. if (child.getVisibility() == View.GONE) {
  107. continue;
  108. }
  109. if (widthUsed + lp.width + lp.leftMargin + lp.rightMargin > widthSpecSize) {
  110. widthUsed = getPaddingLeft() + getPaddingRight();
  111. rowHeight = 0;
  112. }
  113. measureChildWithMargins(child, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed);
  114. int measuredWidth = child.getMeasuredWidth();
  115. int measuredHeight = child.getMeasuredHeight();
  116. widthUsed += measuredWidth;
  117. if (measuredHeight > rowHeight) {
  118. rowHeight = measuredHeight;
  119. heightUsed += measuredHeight - rowHeight;
  120. }
  121. }
  122. }
  123. @Override
  124. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  125. int paddingLeft = getPaddingLeft();
  126. int paddingRight = getPaddingRight();
  127. int paddingTop = getPaddingTop();
  128. int paddingBottom = getPaddingBottom();
  129. final int childCount = getChildCount();
  130. int width = getMeasuredWidth();
  131. int height = getMeasuredHeight();
  132. int rowHeight = 0;
  133. int childTop = paddingTop;
  134. int childLeft = paddingLeft;
  135. for (int i = 0; i < childCount; i++) {
  136. final View child = getChildAt(i);
  137. if (child.getVisibility() != View.GONE) {
  138. int childWidth = child.getMeasuredWidth();
  139. int childHeight = child.getMeasuredHeight();
  140. LayoutParams lp = (LayoutParams) child.getLayoutParams();
  141. int left, top, right, bottom;
  142. if (childLeft + childWidth > width) { // 换行
  143. childTop += rowHeight;
  144. left = paddingLeft + lp.leftMargin;
  145. top = childTop + lp.topMargin;
  146. right = left + childWidth;
  147. bottom = top + childHeight;
  148. child.layout(left, top, right, bottom);
  149. childLeft = right + lp.rightMargin;
  150. rowHeight = childHeight + lp.topMargin + lp.bottomMargin;
  151. } else {
  152. left = childLeft + lp.leftMargin;
  153. top = childTop + lp.topMargin;
  154. right = left + childWidth;
  155. bottom = top + childHeight;
  156. child.layout(left, top, right, bottom);
  157. childLeft = right + lp.rightMargin;
  158. rowHeight = Math.max(rowHeight, childHeight + lp.topMargin + lp.bottomMargin);
  159. }
  160. }
  161. }
  162. }
  163. @Override
  164. public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
  165. return new LayoutParams(getContext(), attrs);
  166. }
  167. @Override
  168. protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
  169. return new LayoutParams(p);
  170. }
  171. public static class LayoutParams extends ViewGroup.MarginLayoutParams {
  172. public LayoutParams(Context c, AttributeSet attrs) {
  173. super(c, attrs);
  174. }
  175. public LayoutParams(int width, int height) {
  176. super(width, height);
  177. }
  178. public LayoutParams(MarginLayoutParams source) {
  179. super(source);
  180. }
  181. public LayoutParams(ViewGroup.LayoutParams source) {
  182. super(source);
  183. }
  184. }
  185. }

5 其他

本文同时发布于简书:https://www.jianshu.com/p/49b89104d828
本章GitHub地址:https://github.com/LittleFogCat/AndroidBookNote/tree/master/chapter04_view

发表评论

表情:
评论列表 (有 0 条评论,391人围观)

还没有评论,来说两句吧...

相关阅读