一、简述

说到RecyclerView大家都很熟悉了,相比于ListView,它具有高度解耦、性能优化等优势,而且现在大多数安卓开发者都已经将RecyclerView用来完全替代ListView和GridView,因为它功能十分强大,但往往功能强大的东西,反而不太好控制,例如今天要说的这个ItemDecoration,ItemDecoration是条目装饰,下面来看看它的强大吧。

二、使用ItemDecoration绘制分割线

想想之前的ListView,要加条分割线,那是分分钟解决的小事,只需要在布局文件中对ListView控件设置其divier属性或者在动态中设置divider即可完成,但RecyclerView却没这么简单了,RecyclerView并没有提供任何直接设置分割线的方法,除了在条目布局中加入这种笨方法之外,也就只能通过ItemDecoration来实现了。

1、自定义ItemDecoration

要使用ItemDecoration,我们得必须先自定义,直接继承ItemDecoration即可。

2、重写getItemOffsets()和onDraw()

1. public class MyDecorationOne extends RecyclerView.ItemDecoration {
2. }

在实现自定义的装饰效果就必须重写getItemOffsets()和onDraw()。

1. public class MyDecorationOne extends RecyclerView.ItemDecoration {
2. /**
3. * 画线
4. */
5. @Override
6. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
7. super.onDraw(c, parent, state);
8. }
9. /**
10. * 设置条目周边的偏移量
11. */
12. @Override
13. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
14. super.getItemOffsets(outRect, view, parent, state);
15. }
16. }

3、解析getItemOffsets()和onDraw()

在理清这两个方法的作用之前,先理清下ItemDecoration的含义,直译:条目装饰,顾名思义,ItemDecoration是对Item起到了装饰作用,更准确的说是对item的周边起到了装饰的作用,通过下面的图应该能帮助你理解这话的含义。

android 更新UI android 更新itemDecoration_gradle

上图中已经说到了,getItemOffsets()就是设置item周边的偏移量(也就是装饰区域的“宽度”)。而onDraw()才是真正实现装饰的回调方法,通过该方法可以在装饰区域任意画画,这里我们来画条分割线。

4、“实现”getItemOffsets()和onDraw()

本例中实现的是线性列表的分割线(即使用LinearLayoutManager)。

1)当线性列表是水平方向时,分割线竖直的;当线性列表是竖直方向时,分割线是水平的。

2)当画竖直分割线时,需要在item的右边偏移出一条线的宽度;当画水平分割线时,需要在item的下边偏移出一条线的高度。

1. /**
2. * 画线
3. */
4. @Override
5. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
6. super.onDraw(c, parent, state);
7. if (orientation == RecyclerView.HORIZONTAL) {
8. drawVertical(c, parent, state);
9. } else if (orientation == RecyclerView.VERTICAL) {
10. drawHorizontal(c, parent, state);
11. }
12. }
13. /**
14. * 设置条目周边的偏移量
15. */
16. @Override
17. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
18. super.getItemOffsets(outRect, view, parent, state);
19. if (orientation == RecyclerView.HORIZONTAL) {
20. //画垂直线
21. outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
22. } else if (orientation == RecyclerView.VERTICAL) {
23. //画水平线
24. outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
25. }
26. }

5、画出一条华丽的分割线

因为getItemOffsets()是相对每个item而言的,即每个item都会偏移出相同的装饰区域。而onDraw()则不同,它是相对Canvas来说的,通俗的说就是要自己找到要画的线的位置,这是自定义ItemDecoration中唯一比较难的地方了。

下图仅对水平分割线的左、上坐标进行图解,其他坐标的计算以此类推。

1. /**
2. * 在构造方法中加载系统自带的分割线(就是ListView用的那个分割线)
3. */
4. public MyDecorationOne(Context context, int orientation) {
5. this.orientation = orientation;
6. int[] attrs = new int[]{android.R.attr.listDivider};
7. TypedArray a = context.obtainStyledAttributes(attrs);
8. mDivider = a.getDrawable(0);
9. a.recycle();
10. }
11. /**
12. * 画竖直分割线
13. */
14. private void drawVertical(Canvas c, RecyclerView parent, RecyclerView.State state) {
15. int childCount = parent.getChildCount();
16. for (int i = 0; i < childCount; i++) {
17. View child = parent.getChildAt(i);
18. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
19. int left = child.getRight() + params.rightMargin;
20. int top = child.getTop() - params.topMargin;
21. int right = left + mDivider.getIntrinsicWidth();
22. int bottom = child.getBottom() + params.bottomMargin;
23. mDivider.setBounds(left, top, right, bottom);
24. mDivider.draw(c);
25. }
26. }
27. /**
28. * 画水平分割线
29. */
30. private void drawHorizontal(Canvas c, RecyclerView parent, RecyclerView.State state) {
31. int childCount = parent.getChildCount();
32. for (int i = 0; i < childCount; i++) {
33. View child = parent.getChildAt(i);
34. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
35. int left = child.getLeft() - params.leftMargin;
36. int top = child.getBottom() + params.bottomMargin;
37. int right = child.getRight() + params.rightMargin;
38. int bottom = top + mDivider.getIntrinsicHeight();
39. mDivider.setBounds(left, top, right, bottom);
40. mDivider.draw(c);
41. }
42. }

android 更新UI android 更新itemDecoration_android 更新UI_02

6、效果

看了下面的效果,你可能会吐槽说,不就是加条分割线吗?要不要这么大费周章?是的,一开始我也是这么想,确实只是为了画条分割线的话,这也太麻烦了,而且项目开发中很少对分割线有多高的定制要求,一般就是ListView那样的,最多就是改改颜色这些。所以本人在之前有对RecyclerView进行过一次封装,可以轻松实现分割线,有兴趣的可以戳我看看!!。好了,下面继续。

android 更新UI android 更新itemDecoration_gradle_03

三、使用ItemDecoration绘制表格

经过上面的学习,相信心中已经对ItemDecoration有个大概的底了,下面再来实现个其他的效果吧——绘制表格。

1、分析

我们知道ItemDecoration就是装饰item周边用的,画条分割线只需要2步,1是在item的下方偏移出一定的宽度,2是在偏移出来的位置上画线。画表格线其实也一样,除了画item下方的线,还画item右边的线就好了(当然换成左边也行)。

2、实现

为了完成表格的样式,本例中使用的是网格列表(即使用GridLayoutManager)。

1)自定义分割线

为了效果更加明显,这里自定义分割线样式。

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:shape="rectangle">
    4. <solid android:color="#f00"/>
    5. <size
    6. android:width="2dp"
    7. android:height="2dp"/>
    8. </shape>

    2)自定义ItemDecoration

    实现上跟画分割线没多大差别,瞄一下就明白了。

    1. public class MyDecorationTwo extends RecyclerView.ItemDecoration {
    2. private final Drawable mDivider;
    3. public MyDecorationTwo(Context context) {
    4. mDivider = context.getResources().getDrawable(R.drawable.divider);
    5. }
    6. @Override
    7. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    8. super.onDraw(c, parent, state);
    9. drawVertical(c, parent);
    10. drawHorizontal(c, parent);
    11. }
    12. private void drawVertical(Canvas c, RecyclerView parent) {
    13. int childCount = parent.getChildCount();
    14. for (int i = 0; i < childCount; i++) {
    15. View child = parent.getChildAt(i);
    16. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    17. int left = child.getRight() + params.rightMargin;
    18. int top = child.getTop() - params.topMargin;
    19. int right = left + mDivider.getIntrinsicWidth();
    20. int bottom = child.getBottom() + params.bottomMargin;
    21. mDivider.setBounds(left, top, right, bottom);
    22. mDivider.draw(c);
    23. }
    24. }
    25. private void drawHorizontal(Canvas c, RecyclerView parent) {
    26. int childCount = parent.getChildCount();
    27. for (int i = 0; i < childCount; i++) {
    28. View child = parent.getChildAt(i);
    29. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    30. int left = child.getLeft() - params.leftMargin;
    31. int top = child.getBottom() + params.bottomMargin;
    32. int right = child.getRight() + params.rightMargin;
    33. int bottom = top + mDivider.getMinimumHeight();
    34. mDivider.setBounds(left, top, right, bottom);
    35. mDivider.draw(c);
    36. }
    37. }
    38. @Override
    39. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    40. super.getItemOffsets(outRect, view, parent, state);
    41. outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight());
    42. }
    43. }

    3、效果(有瑕疵)

    可以看出下面的效果是有问题的,表格的最后一列和最后一行不应该出现边边。

    android 更新UI android 更新itemDecoration_android_04

    4、修复

    既然知道表格的最后一列和最后一行不应该出现边边,那就让最后一列和最后一行的边边消失就好了。有以下几个思路。

    1. 在onDraw()方法中,判断当前列是否为最后一列和判断当前行是否为最后一行来决定是否绘制边边。
    2. 在getItemOffsets()方法中对行列进行判断,来决定是否设置条目偏移量(当偏移量为0时,自然就看不出边边了)。

    这里我选用第二种方式。这里要说明一下,getItemOffsets()有两个,一个是getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state),另一个是getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent),第二个已经过时,但是该方法中有回传当前item的position,所以我选用了过时的getItemOffsets()。

    1. @Override
    2. public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
    3. super.getItemOffsets(outRect, itemPosition, parent);
    4. int right = mDivider.getIntrinsicWidth();
    5. int bottom = mDivider.getIntrinsicHeight();
    6. if (isLastSpan(itemPosition, parent)) {
    7. right = 0;
    8. }
    9. if (isLastRow(itemPosition, parent)) {
    10. bottom = 0;
    11. }
    12. outRect.set(0, 0, right, bottom);
    13. }
    14. public boolean isLastRow(int itemPosition, RecyclerView parent) {
    15. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
    16. if (layoutManager instanceof GridLayoutManager) {
    17. int spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
    18. int itemCount = parent.getAdapter().getItemCount();
    19. if ((itemCount - itemPosition - 1) < spanCount)
    20. return true;
    21. }
    22. return false;
    23. }
    24. public boolean isLastSpan(int itemPosition, RecyclerView parent) {
    25. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
    26. if (layoutManager instanceof GridLayoutManager) {
    27. int spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
    28. if ((itemPosition + 1) % spanCount == 0)
    29. return true;
    30. }
    31. return false;
    32. }

    代码理解上并不难,这里不做多余的解释。

    5、效果(几乎没有瑕疵)

    android 更新UI android 更新itemDecoration_gradle_05

    四、使用ItemDecoration实现侧边字母提示

    上面的两个例子仅仅只是画线,下面的这个例子就来画字吧。先看下效果。

    android 更新UI android 更新itemDecoration_ide_06

    1、分析

    说到底也就是在item左边偏移出来的空间区域中心画个字母而已。下面是大体思路:

    1. 在item的左边偏移出一定的空间(本例偏移量是40dp)。
    2. 在onDraw()时,使用Pinyin工具类获取item中名字拼音的第一个字母。
    3. 判断如果当前是第一个item,就画出字母。
    4. 若不是第一个item则判断当前item的名字字母与上一个字母是否一致,不一致则画出当前字母。

    2、实现

    1)自定义文字拼音工具类

    *该工具类需要用到pinyin4j-2.5.0.jar

    1. public class PinyinUtils {
    2. public static String getPinyin(String str) {
    3. HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    4. format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
    5. format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    6. StringBuilder sb = new StringBuilder();
    7. char[] charArray = str.toCharArray();
    8. for (int i = 0; i < charArray.length; i++) {
    9. char c = charArray[i];
    10. // 如果是空格, 跳过
    11. if (Character.isWhitespace(c)) {
    12. continue;
    13. }
    14. if (c >= -127 && c < 128 || !(c >= 0x4E00 && c <= 0x9FA5)) {
    15. // 肯定不是汉字
    16. sb.append(c);
    17. } else {
    18. String s = "";
    19. try {
    20. // 通过char得到拼音集合. 单 -> dan, shan
    21. s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
    22. sb.append(s);
    23. } catch (BadHanyuPinyinOutputFormatCombination e) {
    24. e.printStackTrace();
    25. sb.append(s);
    26. }
    27. }
    28. }
    29. return sb.toString();
    30. }
    31. }

    2)自定义ItemDecoration

    1. public class MyDecorationThree extends RecyclerView.ItemDecoration {
    2. Context mContext;
    3. List<String> mData;
    4. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    5. public MyDecorationThree(Context context, List<String> data) {
    6. mContext = context;
    7. mData = data;
    8. paint.setTextSize(sp2px(16));
    9. paint.setColor(Color.RED);
    10. }
    11. @Override
    12. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    13. super.onDraw(c, parent, state);
    14. drawLetterToItemLeft(c, parent);
    15. }
    16. private void drawLetterToItemLeft(Canvas c, RecyclerView parent) {
    17. RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
    18. if (!(layoutManager instanceof LinearLayoutManager))
    19. return;
    20. int childCount = parent.getChildCount();
    21. for (int i = 0; i < childCount; i++) {
    22. int position = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition() + i;
    23. View child = parent.getChildAt(i);
    24. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    25. float left = 0;
    26. float top = child.getTop() - params.topMargin;
    27. float right = child.getLeft() - params.leftMargin;
    28. float bottom = child.getBottom() + params.bottomMargin;
    29. float width = right - left;
    30. float height = bottom - (bottom - top) / 2;
    31. //当前名字拼音的第一个字母
    32. String letter = PinyinUtils.getPinyin(mData.get(position)).charAt(0) + "";
    33. if (position == 0) {
    34. drawLetter(letter, width, height, c, parent);
    35. } else {
    36. String preLetter = PinyinUtils.getPinyin(mData.get(position - 1)).charAt(0) + "";
    37. if (!letter.equalsIgnoreCase(preLetter)) {
    38. drawLetter(letter, width, height, c, parent);
    39. }
    40. }
    41. }
    42. }
    43. private void drawLetter(String letter, float width, float height, Canvas c, RecyclerView parent) {
    44. float fontLength = getFontLength(paint, letter);
    45. float fontHeight = getFontHeight(paint);
    46. float tx = (width - fontLength) / 2;
    47. float ty = height - fontHeight / 2 + getFontLeading(paint);
    48. c.drawText(letter, tx, ty, paint);
    49. }
    50. @Override
    51. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    52. super.getItemOffsets(outRect, view, parent, state);
    53. outRect.set(dip2px(40), 0, 0, 0);
    54. }
    55. private int dip2px(int dip) {
    56. float density = mContext.getResources().getDisplayMetrics().density;
    57. int px = (int) (dip * density + 0.5f);
    58. return px;
    59. }
    60. public int sp2px(int sp) {
    61. return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, mContext.getResources().getDisplayMetrics()) + 0.5f);
    62. }
    63. /**
    64. * 返回指定笔和指定字符串的长度
    65. */
    66. private float getFontLength(Paint paint, String str) {
    67. return paint.measureText(str);
    68. }
    69. /**
    70. * 返回指定笔的文字高度
    71. */
    72. private float getFontHeight(Paint paint) {
    73. Paint.FontMetrics fm = paint.getFontMetrics();
    74. return fm.descent - fm.ascent;
    75. }
    76. /**
    77. * 返回指定笔离文字顶部的基准距离
    78. */
    79. private float getFontLeading(Paint paint) {
    80. Paint.FontMetrics fm = paint.getFontMetrics();
    81. return fm.leading - fm.ascent;
    82. }
    83. }