RecyclerView系列之二:从源码中分析为RecyclerView添加分割线

来源:互联网 发布:mac如何运行java程序 编辑:程序博客网 时间:2024/05/21 07:07
  • 今天来解决RecyclerView第二个问题,就是分割线的问题:原生的RecyclerView并没有像ListView那样提供默认的分割线,我们需要自己处理分割线
  • 处理方式为继承RecyclerView的内部类ItemDecoration类,并且复写getItemOffsets()和onDraw()方法.
  • 文章内容包括:
  1. 效果图

  2. 从源码分析RecyclerView分割线的实现方式
  3. 列表和网格分割线的实现
  4. 网格分割线的边界处理
  • 先看对比效果
  •  查看源码RecyclerView中分割线的实现和RecyclerView的内部类ItemDecoration类
  1. public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild {
  2. public RecyclerView(Context context) {
  3. this(context, null);
  4. }
  5. public RecyclerView(Context context, @Nullable AttributeSet attrs) {
  6. this(context, attrs, 0);
  7. }
  8. public RecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
  9. super(context, attrs, defStyle);
  10. ...
  11. }
  12. }
  • 可以知道RecyclerView是ViewGroup的子类
      1. public static abstract class ItemDecoration {
      1. public void onDraw(Canvas c, RecyclerView parent, State state) {
      2. onDraw(c, parent);
      3. }
      1. public void onDrawOver(Canvas c, RecyclerView parent, State state) {
      2. onDrawOver(c, parent);
      3. }
      1. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
      2. getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
      3. parent);
      4. }
      5. }
  • 通过源码的继承类发现:
  1. ItemDecoration没有默认的分割线实现类,只有一个ItemTouchHelper类继承(这个类后面分析Item交互时会讲解到)
  2. 该类内部的几个方法的作用(该文章源码等级为24,过时方法不分析):
  3. getItemOffsets()方法作用是获取每个条目的偏移量,具体值放在参数outRect中,要获取具体的条目位置可通过方法RecyclerView.getChildAdapterPosition(view)获取
  4. onDraw()的作用是分割线的绘制,在传入的参数Canvas中绘制
  5. onDrawOver()分割线绘制完调用的方法(一般没用到)
  • 现在来分析RecyclerView的源码->找出他是如何来绘制分割线的
  1. RecyclerView继承自ViewGroup,自然要看他的三个主要方法onMeasure(),onLayout(),onDraw()和ViewGroup独有的方法measureChild().
  2. 通过查看方法onMeasure()和onLayout()没有发现分割线的影子,而在onDraw()中发现调用了ItemDecoration类的onDraw()方法.
    1. @Override
    2. public void onDraw(Canvas c) {
    3. super.onDraw(c);
    4. final int count = mItemDecorations.size();
    5. for (int i = 0; i < count; i++) {
    6. mItemDecorations.get(i).onDraw(c, this, mState);
    7. }
    8. }
  3. 那必然在measureChild()方法中,会调用分割线的其他方法
    1. public void measureChild(View child, int widthUsed, int heightUsed) {
    2. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    3. final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
    4. widthUsed += insets.left + insets.right;
    5. heightUsed += insets.top + insets.bottom;
    6. final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
    7. getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
    8. canScrollHorizontally());
    9. final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
    10. getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
    11. canScrollVertically());
    12. if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
    13. child.measure(widthSpec, heightSpec);
    14. }
    15. }
  4. 发现调用了方法getItemDecorInsetsForChild();意思是获取每个childView插入的分割线大小.然后再测量childView
    1. Rect getItemDecorInsetsForChild(View child) {
    2. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    3. if (!lp.mInsetsDirty) {
    4. return lp.mDecorInsets;
    5. }
    6. final Rect insets = lp.mDecorInsets;
    7. insets.set(0, 0, 0, 0);
    8. final int decorCount = mItemDecorations.size();
    9. for (int i = 0; i < decorCount; i++) {
    10. mTempRect.set(0, 0, 0, 0);
    11. mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
    12. insets.left += mTempRect.left;
    13. insets.top += mTempRect.top;
    14. insets.right += mTempRect.right;
    15. insets.bottom += mTempRect.bottom;
    16. }
    17. lp.mInsetsDirty = false;
    18. return insets;
    19. }
  5. 分割线偏移量方法getItemOffsets()方法也找到了最终调用的位置
  • 了解了RecyclerView的分割线源码实现过程,要实现就不难了
  1. 列表分割线的代码实现
    1. public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    2. private static final int[] ATTRS = new int[]{
    3. android.R.attr.listDivider
    4. };
    5. public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    6. public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
    7. private Drawable mDivider;
    8. private int mOrientation;
    9. public DividerItemDecoration(Context context, int orientation) {
    10. final TypedArray a = context.obtainStyledAttributes(ATTRS);
    11. mDivider = a.getDrawable(0);
    12. a.recycle();
    13. setOrientation(orientation);
    14. }
    15. public void setOrientation(int orientation) {
    16. if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
    17. throw new IllegalArgumentException("invalid orientation");
    18. }
    19. mOrientation = orientation;
    20. }
    21. @Override
    22. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    23. if (mOrientation == VERTICAL_LIST) {
    24. drawVertical(c, parent);
    25. } else {
    26. drawHorizontal(c, parent);
    27. }
    28. }
    29. /**
    30. * 垂直方向分割线
    31. * @param c
    32. * @param parent
    33. */
    34. public void drawVertical(Canvas c, RecyclerView parent) {
    35. final int left = parent.getPaddingLeft();
    36. final int right = parent.getWidth() - parent.getPaddingRight();
    37. final int childCount = parent.getChildCount();
    38. for (int i = 0; i < childCount; i++) {
    39. final View child = parent.getChildAt(i);
    40. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
    41. .getLayoutParams();
    42. final int top = child.getBottom() + params.bottomMargin;
    43. final int bottom = top + mDivider.getIntrinsicHeight();
    44. mDivider.setBounds(left, top, right, bottom);
    45. mDivider.draw(c);
    46. }
    47. }
    48. public void drawHorizontal(Canvas c, RecyclerView parent) {
    49. final int top = parent.getPaddingTop();
    50. final int bottom = parent.getHeight() - parent.getPaddingBottom();
    51. final int childCount = parent.getChildCount();
    52. for (int i = 0; i < childCount; i++) {
    53. final View child = parent.getChildAt(i);
    54. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
    55. .getLayoutParams();
    56. final int left = child.getRight() + params.rightMargin;
    57. final int right = left + mDivider.getIntrinsicHeight();
    58. mDivider.setBounds(left, top, right, bottom);
    59. mDivider.draw(c);
    60. }
    61. }
    62. @Override
    63. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    64. if (mOrientation == VERTICAL_LIST) {
    65. outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    66. } else {
    67. outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
    68. }
    69. }
    70. }
  2. 网格分割线的代码实现-注意最后一行和最后一列不添加分割线
  1. public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {
  2. private String TAG = this.getClass().getSimpleName();
  3. private static final int[] ATTRS = new int[]{
  4. android.R.attr.listDivider
  5. };
  6. private Drawable mDivider;
  7. public DividerGridItemDecoration(Context context) {
  8. final TypedArray a = context.obtainStyledAttributes(ATTRS);
  9. mDivider = a.getDrawable(0);
  10. a.recycle();
  11. }
  12. @Override
  13. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
  14. drawVertical(c, parent);
  15. drawHorizontal(c, parent);
  16. }
  17. /**
  18. * 水平方向分割线
  19. * @param c
  20. * @param parent
  21. */
  22. public void drawHorizontal(Canvas c, RecyclerView parent) {
  23. final int childCount = parent.getChildCount();
  24. for (int i = 0; i < childCount; i++) {
  25. if (isLastRow(parent, i, getSpanCount(parent), childCount))//最后一行不绘制
  26. continue;
  27. final View child = parent.getChildAt(i);
  28. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  29. .getLayoutParams();
  30. final int left = child.getLeft() - params.leftMargin;
  31. final int right = child.getRight() + params.rightMargin;
  32. final int top = child.getBottom() + params.bottomMargin;
  33. final int bottom = top + mDivider.getIntrinsicHeight();
  34. mDivider.setBounds(left, top, right, bottom);
  35. mDivider.draw(c);
  36. }
  37. }
  38. public void drawVertical(Canvas c, RecyclerView parent) {
  39. final int childCount = parent.getChildCount();
  40. for (int i = 0; i < childCount; i++) {
  41. final View child = parent.getChildAt(i);
  42. if (isLastColumn(parent, i, getSpanCount(parent), childCount))//最后一列不绘制
  43. continue;
  44. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  45. .getLayoutParams();
  46. final int top = child.getTop() - params.topMargin;
  47. final int bottom = child.getBottom() + params.bottomMargin;
  48. final int left = child.getRight() + params.rightMargin;
  49. final int right = left + mDivider.getIntrinsicWidth();
  50. mDivider.setBounds(left, top, right, bottom);
  51. mDivider.draw(c);
  52. }
  53. }
  54. @Override
  55. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
  56. int right = mDivider.getIntrinsicWidth();
  57. int bottom = mDivider.getIntrinsicHeight();
  58. outRect.set(0, 0, right, bottom);
  59. }
  60. /**
  61. * 是否是最后一列
  62. *
  63. * @param parent
  64. * @param currChildPos
  65. * @param spanCount
  66. * @param itemCount
  67. * @return
  68. */
  69. private boolean isLastColumn(RecyclerView parent, int currChildPos, int spanCount, int itemCount) {
  70. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
  71. if (layoutManager != null && layoutManager instanceof GridLayoutManager) {
  72. if ((currChildPos + 1) % spanCount == 0) {
  73. return true;
  74. }
  75. } else if (layoutManager != null && layoutManager instanceof StaggeredGridLayoutManager) {
  76. //瀑布流也有两种方向
  77. StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
  78. int orientation = staggeredGridLayoutManager.getOrientation();
  79. if (orientation == StaggeredGridLayoutManager.VERTICAL) {//垂直
  80. if ((currChildPos + 1) % spanCount == 0) {
  81. return true;
  82. }
  83. } else {
  84. if (itemCount % spanCount != 0) {
  85. itemCount = itemCount - itemCount % spanCount;
  86. if (currChildPos >= itemCount) {//这种判断方式在item最后一行未填满的情况下可行
  87. return true;
  88. }
  89. } else {//最后一行填满的情况处理
  90. itemCount = itemCount - spanCount;
  91. if (currChildPos >= itemCount) {
  92. return true;
  93. }
  94. }
  95. }
  96. }
  97. return false;
  98. }
  99. /**
  100. * 是否是最后一行
  101. *
  102. * @param parent
  103. * @param currChildPos
  104. * @param spanCount
  105. * @param itemCount
  106. * @return
  107. */
  108. private boolean isLastRow(RecyclerView parent, int currChildPos, int spanCount, int itemCount) {
  109. boolean result = false;
  110. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
  111. if (layoutManager != null && layoutManager instanceof GridLayoutManager) {
  112. if (itemCount % spanCount != 0) {
  113. itemCount = itemCount - itemCount % spanCount;
  114. if (currChildPos >= itemCount) {//这种判断方式在item最后一行未填满的情况下可行
  115. return true;
  116. }
  117. } else {//最后一行填满的情况处理
  118. itemCount = itemCount - spanCount;
  119. if (currChildPos >= itemCount) {
  120. return true;
  121. }
  122. }
  123. } else if (layoutManager != null && layoutManager instanceof StaggeredGridLayoutManager) {
  124. //瀑布流也有两种方向
  125. StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
  126. int orientation = staggeredGridLayoutManager.getOrientation();
  127. if (orientation == StaggeredGridLayoutManager.VERTICAL) {//垂直
  128. if (itemCount % spanCount != 0) {
  129. itemCount = itemCount - itemCount % spanCount;
  130. if (currChildPos >= itemCount) {//这种判断方式在item最后一行未填满的情况下可行
  131. return true;
  132. }
  133. } else {//最后一行填满的情况处理
  134. itemCount = itemCount - spanCount;
  135. if (currChildPos >= itemCount) {
  136. return true;
  137. }
  138. }
  139. } else {
  140. if (currChildPos % spanCount == 0) {
  141. return true;
  142. }
  143. }
  144. }
  145. return false;
  146. }
  147. /**
  148. * 获取当前item在recycler的adapter的位置
  149. *
  150. * @param parent
  151. * @param view
  152. * @return
  153. */
  154. private int getCurrentChildPosition(RecyclerView parent, View view) {
  155. return parent.getChildAdapterPosition(view);
  156. }
  157. private int getSpanCount(RecyclerView parent) {
  158. int spanCount = -1;
  159. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
  160. if (layoutManager instanceof GridLayoutManager) {
  161. GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
  162. spanCount = gridLayoutManager.getSpanCount();
  163. } else if (layoutManager instanceof StaggeredGridLayoutManager) {
  164. StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
  165. spanCount = staggeredGridLayoutManager.getSpanCount();
  166. }
  167. return spanCount;
  168. }
  169. }
  • 总结:在处理最后一行分割线不绘制的时候发现,在偏移量方法getItemOffset()方法中处理并不起效果,为了准确我将判断最后一行和最后一列的childView的分割线放到绘制方法中调用,是最后一行就不绘制.
  • 网上的判断最后一行的方法有缺陷,未考虑最后一行是否填满,在未填满时,绘制没有问题,这也反映了很多人的博客都是复制粘贴过来,而没有自己真正考虑过.


0 0
原创粉丝点击