当前位置:   article > 正文

Android RecyclerView 使用完全解析 体验艺术般的控件

学会recyclerview控件的用法

转载请标明出处:
http://blog.csdn.net/lmj623565791/article/details/45059587
本文出自:【张鸿洋的博客】

概述

RecyclerView出现已经有一段时间了,相信大家肯定不陌生了,大家可以通过导入support-v7对其进行使用。
据官方的介绍,该控件用于在有限的窗口中展示大量数据集,其实这样功能的控件我们并不陌生,例如:ListView、GridView。

那么有了ListView、GridView为什么还需要RecyclerView这样的控件呢?整体上看RecyclerView架构,提供了一种插拔式的体验,高度的解耦,异常的灵活,通过设置它提供的不同LayoutManager,ItemDecoration , ItemAnimator实现令人瞠目的效果。

  • 你想要控制其显示的方式,请通过布局管理器LayoutManager
  • 你想要控制Item间的间隔(可绘制),请通过ItemDecoration
  • 你想要控制Item增删的动画,请通过ItemAnimator
  • 你想要控制点击、长按事件,请自己写(擦,这点尼玛。)

基本使用

鉴于我们对于ListView的使用特别的熟悉,对比下RecyclerView的使用代码:

  1. mRecyclerView = findView(R.id.id_recyclerview);
  2. //设置布局管理器
  3. mRecyclerView.setLayoutManager(layout);
  4. //设置adapter
  5. mRecyclerView.setAdapter(adapter)
  6. //设置Item增加、移除动画
  7. mRecyclerView.setItemAnimator(new DefaultItemAnimator());
  8. //添加分割线
  9. mRecyclerView.addItemDecoration(new DividerItemDecoration(
  10. getActivity(), DividerItemDecoration.HORIZONTAL_LIST));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

ok,相比较于ListView的代码,ListView可能只需要去设置一个adapter就能正常使用了。而RecyclerView基本需要上面一系列的步骤,那么为什么会添加这么多的步骤呢?

那么就必须解释下RecyclerView的这个名字了,从它类名上看,RecyclerView代表的意义是,我只管Recycler View,也就是说RecyclerView只管回收与复用View,其他的你可以自己去设置。可以看出其高度的解耦,给予你充分的定制自由(所以你才可以轻松的通过这个控件实现ListView,GirdView,瀑布流等效果)。

Just like ListView

  • Activity
  1. package com.zhy.sample.demo_recyclerview;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.os.Bundle;
  5. import android.support.v7.app.ActionBarActivity;
  6. import android.support.v7.widget.LinearLayoutManager;
  7. import android.support.v7.widget.RecyclerView;
  8. import android.support.v7.widget.RecyclerView.ViewHolder;
  9. import android.view.LayoutInflater;
  10. import android.view.View;
  11. import android.view.ViewGroup;
  12. import android.widget.TextView;
  13. public class HomeActivity extends ActionBarActivity
  14. {
  15. private RecyclerView mRecyclerView;
  16. private List<String> mDatas;
  17. private HomeAdapter mAdapter;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState)
  20. {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_single_recyclerview);
  23. initData();
  24. mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
  25. mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
  26. mRecyclerView.setAdapter(mAdapter = new HomeAdapter());
  27. }
  28. protected void initData()
  29. {
  30. mDatas = new ArrayList<String>();
  31. for (int i = 'A'; i < 'z'; i++)
  32. {
  33. mDatas.add("" + (char) i);
  34. }
  35. }
  36. class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>
  37. {
  38. @Override
  39. public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
  40. {
  41. MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
  42. HomeActivity.this).inflate(R.layout.item_home, parent,
  43. false));
  44. return holder;
  45. }
  46. @Override
  47. public void onBindViewHolder(MyViewHolder holder, int position)
  48. {
  49. holder.tv.setText(mDatas.get(position));
  50. }
  51. @Override
  52. public int getItemCount()
  53. {
  54. return mDatas.size();
  55. }
  56. class MyViewHolder extends ViewHolder
  57. {
  58. TextView tv;
  59. public MyViewHolder(View view)
  60. {
  61. super(view);
  62. tv = (TextView) view.findViewById(R.id.id_num);
  63. }
  64. }
  65. }
  66. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • Activity的布局文件
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <android.support.v7.widget.RecyclerView
  6. android:id="@+id/id_recyclerview"
  7. android:divider="#ffff0000"
  8. android:dividerHeight="10dp"
  9. android:layout_width="match_parent"
  10. android:layout_height="match_parent" />
  11. </RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • Item的布局文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:background="#44ff0000"
  5. android:layout_height="wrap_content" >
  6. <TextView
  7. android:id="@+id/id_num"
  8. android:layout_width="match_parent"
  9. android:layout_height="50dp"
  10. android:gravity="center"
  11. android:text="1" />
  12. </FrameLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

这么看起来用法与ListView的代码基本一致哈~~
看下效果图:

20150415145840351

看起来好丑,Item间应该有个分割线,当你去找时,你会发现RecyclerView并没有支持divider这样的属性。那么怎么办,你可以给Item的布局去设置margin,当然了这种方式不够优雅,我们文章开始说了,我们可以自由的去定制它,当然我们的分割线也是可以定制的。

ItemDecoration

我们可以通过该方法添加分割线:
mRecyclerView.addItemDecoration()
该方法的参数为RecyclerView.ItemDecoration,该类为抽象类,官方目前并没有提供默认的实现类(我觉得最好能提供几个)。
该类的源码:

  1. public static abstract class ItemDecoration {
  2. public void onDraw(Canvas c, RecyclerView parent, State state) {
  3. onDraw(c, parent);
  4. }
  5. public void onDrawOver(Canvas c, RecyclerView parent, State state) {
  6. onDrawOver(c, parent);
  7. }
  8. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
  9. getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
  10. parent);
  11. }
  12. @Deprecated
  13. public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
  14. outRect.set(0, 0, 0, 0);
  15. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

当我们调用mRecyclerView.addItemDecoration()方法添加decoration的时候,RecyclerView在绘制的时候,去会绘制decorator,即调用该类的onDraw和onDrawOver方法,

  • onDraw方法先于drawChildren
  • onDrawOver在drawChildren之后,一般我们选择复写其中一个即可。
  • getItemOffsets 可以通过outRect.set()为每个Item设置一定的偏移量,主要用于绘制Decorator。

接下来我们看一个RecyclerView.ItemDecoration的实现类,该类很好的实现了RecyclerView添加分割线(当使用LayoutManager为LinearLayoutManager时)。
该类参考自:DividerItemDecoration

  1. package com.zhy.sample.demo_recyclerview;
  2. /*
  3. * Copyright (C) 2014 The Android Open Source Project
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * limitations under the License.
  7. */
  8. import android.content.Context;
  9. import android.content.res.TypedArray;
  10. import android.graphics.Canvas;
  11. import android.graphics.Rect;
  12. import android.graphics.drawable.Drawable;
  13. import android.support.v7.widget.LinearLayoutManager;
  14. import android.support.v7.widget.RecyclerView;
  15. import android.support.v7.widget.RecyclerView.State;
  16. import android.util.Log;
  17. import android.view.View;
  18. /**
  19. * This class is from the v7 samples of the Android SDK. It's not by me!
  20. * <p/>
  21. * See the license above for details.
  22. */
  23. public class DividerItemDecoration extends RecyclerView.ItemDecoration {
  24. private static final int[] ATTRS = new int[]{
  25. android.R.attr.listDivider
  26. };
  27. public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
  28. public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
  29. private Drawable mDivider;
  30. private int mOrientation;
  31. public DividerItemDecoration(Context context, int orientation) {
  32. final TypedArray a = context.obtainStyledAttributes(ATTRS);
  33. mDivider = a.getDrawable(0);
  34. a.recycle();
  35. setOrientation(orientation);
  36. }
  37. public void setOrientation(int orientation) {
  38. if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
  39. throw new IllegalArgumentException("invalid orientation");
  40. }
  41. mOrientation = orientation;
  42. }
  43. @Override
  44. public void onDraw(Canvas c, RecyclerView parent) {
  45. Log.v("recyclerview - itemdecoration", "onDraw()");
  46. if (mOrientation == VERTICAL_LIST) {
  47. drawVertical(c, parent);
  48. } else {
  49. drawHorizontal(c, parent);
  50. }
  51. }
  52. public void drawVertical(Canvas c, RecyclerView parent) {
  53. final int left = parent.getPaddingLeft();
  54. final int right = parent.getWidth() - parent.getPaddingRight();
  55. final int childCount = parent.getChildCount();
  56. for (int i = 0; i < childCount; i++) {
  57. final View child = parent.getChildAt(i);
  58. android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
  59. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  60. .getLayoutParams();
  61. final int top = child.getBottom() + params.bottomMargin;
  62. final int bottom = top + mDivider.getIntrinsicHeight();
  63. mDivider.setBounds(left, top, right, bottom);
  64. mDivider.draw(c);
  65. }
  66. }
  67. public void drawHorizontal(Canvas c, RecyclerView parent) {
  68. final int top = parent.getPaddingTop();
  69. final int bottom = parent.getHeight() - parent.getPaddingBottom();
  70. final int childCount = parent.getChildCount();
  71. for (int i = 0; i < childCount; i++) {
  72. final View child = parent.getChildAt(i);
  73. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  74. .getLayoutParams();
  75. final int left = child.getRight() + params.rightMargin;
  76. final int right = left + mDivider.getIntrinsicHeight();
  77. mDivider.setBounds(left, top, right, bottom);
  78. mDivider.draw(c);
  79. }
  80. }
  81. @Override
  82. public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
  83. if (mOrientation == VERTICAL_LIST) {
  84. outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
  85. } else {
  86. outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
  87. }
  88. }
  89. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110

该实现类可以看到通过读取系统主题中的 android.R.attr.listDivider作为Item间的分割线,并且支持横向和纵向。如果你不清楚它是怎么做到的读取系统的属性用于自身,请参考我的另一篇博文:Android 深入理解Android中的自定义属性

获取到listDivider以后,该属性的值是个Drawable,在getItemOffsets中,outRect去设置了绘制的范围。onDraw中实现了真正的绘制。

我们在原来的代码中添加一句:

  1. mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
  2. DividerItemDecoration.VERTICAL_LIST));
  • 1
  • 2

ok,现在再运行,就可以看到分割线的效果了。

20150415145931083

该分割线是系统默认的,你可以在theme.xml中找到该属性的使用情况。那么,使用系统的listDivider有什么好处呢?就是方便我们去随意的改变,该属性我们可以直接声明在:

  1. <!-- Application theme. -->
  2. <style name="AppTheme" parent="AppBaseTheme">
  3. <item name="android:listDivider">@drawable/divider_bg</item>
  4. </style>
  • 1
  • 2
  • 3
  • 4

然后自己写个drawable即可,下面我们换一种分隔符:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle" >
  4. <gradient
  5. android:centerColor="#ff00ff00"
  6. android:endColor="#ff0000ff"
  7. android:startColor="#ffff0000"
  8. android:type="linear" />
  9. <size android:height="4dp"/>
  10. </shape>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

现在的样子是:

20150415151013289

当然了,你可以根据自己的需求,去随意的绘制,反正是画出来的,随便玩~~

ok,看到这,你可能觉得,这玩意真尼玛麻烦,完全不能比拟的心爱的ListView。那么继续看。

LayoutManager

好了,上面实现了类似ListView样子的Demo,通过使用其默认的LinearLayoutManager。

RecyclerView.LayoutManager吧,这是一个抽象类,好在系统提供了3个实现类:

  1. LinearLayoutManager 现行管理器,支持横向、纵向。
  2. GridLayoutManager 网格布局管理器
  3. StaggeredGridLayoutManager 瀑布就式布局管理器

上面我们已经初步体验了下LinearLayoutManager,接下来看GridLayoutManager。

  • GridLayoutManager

我们尝试去实现类似GridView,秒秒钟的事情:

  1. //mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
  2. mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
  • 1
  • 2

只需要修改LayoutManager即可,还是很nice的。

当然了,改为GridLayoutManager以后,对于分割线,前面的DividerItemDecoration就不适用了,主要是因为它在绘制的时候,比如水平线,针对每个child的取值为:

  1. final int left = parent.getPaddingLeft();
  2. final int right = parent.getWidth() - parent.getPaddingRight();
  • 1
  • 2

因为每个Item一行,这样是没问题的。而GridLayoutManager时,一行有多个childItem,这样就多次绘制了,并且GridLayoutManager时,Item如果为最后一列(则右边无间隔线)或者为最后一行(底部无分割线)。

针对上述,我们编写了DividerGridItemDecoration

  1. package com.zhy.sample.demo_recyclerview;
  2. import android.content.Context;
  3. import android.content.res.TypedArray;
  4. import android.graphics.Canvas;
  5. import android.graphics.Rect;
  6. import android.graphics.drawable.Drawable;
  7. import android.support.v7.widget.GridLayoutManager;
  8. import android.support.v7.widget.RecyclerView;
  9. import android.support.v7.widget.RecyclerView.LayoutManager;
  10. import android.support.v7.widget.RecyclerView.State;
  11. import android.support.v7.widget.StaggeredGridLayoutManager;
  12. import android.view.View;
  13. /**
  14. *
  15. * @author zhy
  16. *
  17. */
  18. public class DividerGridItemDecoration extends RecyclerView.ItemDecoration
  19. {
  20. private static final int[] ATTRS = new int[] { android.R.attr.listDivider };
  21. private Drawable mDivider;
  22. public DividerGridItemDecoration(Context context)
  23. {
  24. final TypedArray a = context.obtainStyledAttributes(ATTRS);
  25. mDivider = a.getDrawable(0);
  26. a.recycle();
  27. }
  28. @Override
  29. public void onDraw(Canvas c, RecyclerView parent, State state)
  30. {
  31. drawHorizontal(c, parent);
  32. drawVertical(c, parent);
  33. }
  34. private int getSpanCount(RecyclerView parent)
  35. {
  36. // 列数
  37. int spanCount = -1;
  38. LayoutManager layoutManager = parent.getLayoutManager();
  39. if (layoutManager instanceof GridLayoutManager)
  40. {
  41. spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
  42. } else if (layoutManager instanceof StaggeredGridLayoutManager)
  43. {
  44. spanCount = ((StaggeredGridLayoutManager) layoutManager)
  45. .getSpanCount();
  46. }
  47. return spanCount;
  48. }
  49. public void drawHorizontal(Canvas c, RecyclerView parent)
  50. {
  51. int childCount = parent.getChildCount();
  52. for (int i = 0; i < childCount; i++)
  53. {
  54. final View child = parent.getChildAt(i);
  55. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  56. .getLayoutParams();
  57. final int left = child.getLeft() - params.leftMargin;
  58. final int right = child.getRight() + params.rightMargin
  59. + mDivider.getIntrinsicWidth();
  60. final int top = child.getBottom() + params.bottomMargin;
  61. final int bottom = top + mDivider.getIntrinsicHeight();
  62. mDivider.setBounds(left, top, right, bottom);
  63. mDivider.draw(c);
  64. }
  65. }
  66. public void drawVertical(Canvas c, RecyclerView parent)
  67. {
  68. final int childCount = parent.getChildCount();
  69. for (int i = 0; i < childCount; i++)
  70. {
  71. final View child = parent.getChildAt(i);
  72. final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
  73. .getLayoutParams();
  74. final int top = child.getTop() - params.topMargin;
  75. final int bottom = child.getBottom() + params.bottomMargin;
  76. final int left = child.getRight() + params.rightMargin;
  77. final int right = left + mDivider.getIntrinsicWidth();
  78. mDivider.setBounds(left, top, right, bottom);
  79. mDivider.draw(c);
  80. }
  81. }
  82. private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
  83. int childCount)
  84. {
  85. LayoutManager layoutManager = parent.getLayoutManager();
  86. if (layoutManager instanceof GridLayoutManager)
  87. {
  88. if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
  89. {
  90. return true;
  91. }
  92. } else if (layoutManager instanceof StaggeredGridLayoutManager)
  93. {
  94. int orientation = ((StaggeredGridLayoutManager) layoutManager)
  95. .getOrientation();
  96. if (orientation == StaggeredGridLayoutManager.VERTICAL)
  97. {
  98. if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
  99. {
  100. return true;
  101. }
  102. } else
  103. {
  104. childCount = childCount - childCount % spanCount;
  105. if (pos >= childCount)// 如果是最后一列,则不需要绘制右边
  106. return true;
  107. }
  108. }
  109. return false;
  110. }
  111. private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
  112. int childCount)
  113. {
  114. LayoutManager layoutManager = parent.getLayoutManager();
  115. if (layoutManager instanceof GridLayoutManager)
  116. {
  117. childCount = childCount - childCount % spanCount;
  118. if (pos >= childCount)// 如果是最后一行,则不需要绘制底部
  119. return true;
  120. } else if (layoutManager instanceof StaggeredGridLayoutManager)
  121. {
  122. int orientation = ((StaggeredGridLayoutManager) layoutManager)
  123. .getOrientation();
  124. // StaggeredGridLayoutManager 且纵向滚动
  125. if (orientation == StaggeredGridLayoutManager.VERTICAL)
  126. {
  127. childCount = childCount - childCount % spanCount;
  128. // 如果是最后一行,则不需要绘制底部
  129. if (pos >= childCount)
  130. return true;
  131. } else
  132. // StaggeredGridLayoutManager 且横向滚动
  133. {
  134. // 如果是最后一行,则不需要绘制底部
  135. if ((pos + 1) % spanCount == 0)
  136. {
  137. return true;
  138. }
  139. }
  140. }
  141. return false;
  142. }
  143. @Override
  144. public void getItemOffsets(Rect outRect, int itemPosition,
  145. RecyclerView parent)
  146. {
  147. int spanCount = getSpanCount(parent);
  148. int childCount = parent.getAdapter().getItemCount();
  149. if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,则不需要绘制底部
  150. {
  151. outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
  152. } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,则不需要绘制右边
  153. {
  154. outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
  155. } else
  156. {
  157. outRect.set(0, 0, mDivider.getIntrinsicWidth(),
  158. mDivider.getIntrinsicHeight());
  159. }
  160. }
  161. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178

主要在getItemOffsets方法中,去判断如果是最后一行,则不需要绘制底部;如果是最后一列,则不需要绘制右边,整个判断也考虑到了StaggeredGridLayoutManager的横向和纵向,所以稍稍有些复杂。最重要还是去理解,如何绘制什么的不重要。一般如果仅仅是希望有空隙,还是去设置item的margin方便。

最后的效果是:

20150415150026088

ok,看到这,你可能还觉得RecyclerView不够强大?

但是如果我们有这么个需求,纵屏的时候显示为ListView,横屏的时候显示两列的GridView,我们RecyclerView可以轻松搞定,而如果使用ListView去实现还是需要点功夫的~~~

当然了,这只是皮毛,下面让你心服口服。

  • StaggeredGridLayoutManager

瀑布流式的布局,其实他可以实现GridLayoutManager一样的功能,仅仅按照下列代码:

  1. // mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
  2. mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
  • 1
  • 2

这两种写法显示的效果是一致的,但是注意StaggeredGridLayoutManager构造的第二个参数传一个orientation,如果传入的是StaggeredGridLayoutManager.VERTICAL代表有多少列;那么传入的如果是StaggeredGridLayoutManager.HORIZONTAL就代表有多少行,比如本例如果改为:

  1. mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
  2. StaggeredGridLayoutManager.HORIZONTAL));
  • 1
  • 2

那么效果为:

20150415150125431

可以看到,固定为4行,变成了左右滑动。有一点需要注意,如果是横向的时候,item的宽度需要注意去设置,毕竟横向的宽度没有约束了,应为控件可以横向滚动了。
如果你需要一样横向滚动的GridView,那么恭喜你。

ok,接下来准备看大招,如果让你去实现个瀑布流,最起码不是那么随意就可以实现的吧?但是,如果使用RecyclerView,分分钟的事。
那么如何实现?其实你什么都不用做,只要使用StaggeredGridLayoutManager我们就已经实现了,只是上面的item布局我们使用了固定的高度,下面我们仅仅在适配器的onBindViewHolder方法中为我们的item设置个随机的高度(代码就不贴了,最后会给出源码下载地址),看看效果图:

20150415193645985

是不是棒棒哒,通过RecyclerView去实现ListView、GridView、瀑布流的效果基本上没有什么区别,而且可以仅仅通过设置不同的LayoutManager即可实现。

还有更nice的地方,就在于item增加、删除的动画也是可配置的。接下来看一下ItemAnimator。

ItemAnimator

ItemAnimator也是一个抽象类,好在系统为我们提供了一种默认的实现类,期待系统多
添加些默认的实现。

借助默认的实现,当Item添加和移除的时候,添加动画效果很简单:

  1. // 设置item动画
  2. mRecyclerView.setItemAnimator(new DefaultItemAnimator());
  • 1
  • 2

系统为我们提供了一个默认的实现,我们为我们的瀑布流添加以上一行代码,效果为:

20150415194114149

如果是GridLayoutManager呢?动画效果为:

20150415150130083

注意,这里更新数据集不是用adapter.notifyDataSetChanged()而是
notifyItemInserted(position)notifyItemRemoved(position)
否则没有动画效果。
上述为adapter中添加了两个方法:

  1. public void addData(int position) {
  2. mDatas.add(position, "Insert One");
  3. notifyItemInserted(position);
  4. }
  5. public void removeData(int position) {
  6. mDatas.remove(position);
  7. notifyItemRemoved(position);
  8. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Activity中点击MenuItem触发:

  1. @Override
  2. public boolean onCreateOptionsMenu(Menu menu)
  3. {
  4. getMenuInflater().inflate(R.menu.main, menu);
  5. return super.onCreateOptionsMenu(menu);
  6. }
  7. @Override
  8. public boolean onOptionsItemSelected(MenuItem item)
  9. {
  10. switch (item.getItemId())
  11. {
  12. case R.id.id_action_add:
  13. mAdapter.addData(1);
  14. break;
  15. case R.id.id_action_delete:
  16. mAdapter.removeData(1);
  17. break;
  18. }
  19. return true;
  20. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

好了,到这我对这个控件已经不是一般的喜欢了~~~

当然了只提供了一种动画,那么我们肯定可以去自定义各种nice的动画效果。
高兴的是,github上已经有很多类似的项目了,这里我们直接引用下:RecyclerViewItemAnimators,大家自己下载查看。
提供了SlideInOutLeftItemAnimator,SlideInOutRightItemAnimator,
SlideInOutTopItemAnimator,SlideInOutBottomItemAnimator等动画效果。

Click and LongClick

不过一个挺郁闷的地方就是,系统没有提供ClickListener和LongClickListener。
不过我们也可以自己去添加,只是会多了些代码而已。
实现的方式比较多,你可以通过mRecyclerView.addOnItemTouchListener去监听然后去判断手势,
当然你也可以通过adapter中自己去提供回调,这里我们选择后者,前者的方式,大家有兴趣自己去实现。

那么代码也比较简单:

  1. class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>
  2. {
  3. //...
  4. public interface OnItemClickLitener
  5. {
  6. void onItemClick(View view, int position);
  7. void onItemLongClick(View view , int position);
  8. }
  9. private OnItemClickLitener mOnItemClickLitener;
  10. public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener)
  11. {
  12. this.mOnItemClickLitener = mOnItemClickLitener;
  13. }
  14. @Override
  15. public void onBindViewHolder(final MyViewHolder holder, final int position)
  16. {
  17. holder.tv.setText(mDatas.get(position));
  18. // 如果设置了回调,则设置点击事件
  19. if (mOnItemClickLitener != null)
  20. {
  21. holder.itemView.setOnClickListener(new OnClickListener()
  22. {
  23. @Override
  24. public void onClick(View v)
  25. {
  26. int pos = holder.getLayoutPosition();
  27. mOnItemClickLitener.onItemClick(holder.itemView, pos);
  28. }
  29. });
  30. holder.itemView.setOnLongClickListener(new OnLongClickListener()
  31. {
  32. @Override
  33. public boolean onLongClick(View v)
  34. {
  35. int pos = holder.getLayoutPosition();
  36. mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
  37. return false;
  38. }
  39. });
  40. }
  41. }
  42. //...
  43. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

adapter中自己定义了个接口,然后在onBindViewHolder中去为holder.itemView去设置相应
的监听最后回调我们设置的监听。

最后别忘了给item添加一个drawable:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >
  3. <item android:state_pressed="true" android:drawable="@color/color_item_press"></item>
  4. <item android:drawable="@color/color_item_normal"></item>
  5. </selector>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Activity中去设置监听:

  1. mAdapter.setOnItemClickLitener(new OnItemClickLitener()
  2. {
  3. @Override
  4. public void onItemClick(View view, int position)
  5. {
  6. Toast.makeText(HomeActivity.this, position + " click",
  7. Toast.LENGTH_SHORT).show();
  8. }
  9. @Override
  10. public void onItemLongClick(View view, int position)
  11. {
  12. Toast.makeText(HomeActivity.this, position + " long click",
  13. Toast.LENGTH_SHORT).show();
  14. mAdapter.removeData(position);
  15. }
  16. });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

测试效果:

20150415194800546

ok,到此我们基本介绍了RecylerView常见用法,包含了:

  • 系统提供了几种LayoutManager的使用;
  • 如何通过自定义ItemDecoration去设置分割线,或者一些你想作为分隔的drawable,注意这里
    巧妙的使用了系统的listDivider属性,你可以尝试添加使用divider和dividerHeight属性。
  • 如何使用ItemAnimator为RecylerView去添加Item移除、添加的动画效果。
  • 介绍了如何添加ItemClickListener与ItemLongClickListener。

可以看到RecyclerView可以实现:

整个体验下来,感觉这种插拔式的设计太棒了,如果系统再能提供一些常用的分隔符,多添加些动画效果就更好了。

通过简单改变下LayoutManager,就可以产生不同的效果,那么我们可以根据手机屏幕的宽度去动态设置LayoutManager,屏幕宽度一般的,显示为ListView;宽度稍大的显示两列的GridView或者瀑布流(或者横纵屏幕切换时变化,有点意思~);显示的列数和宽度成正比。甚至某些特殊屏幕,让其横向滑动~~再选择一个nice的动画效果,相信这种插件式的编码体验一定会让你迅速爱上RecyclerView。

参考资料

Android 自定义RecyclerView 实现真正的Gallery效果

A First Glance at Android’s RecyclerView

https://github.com/gabrielemariotti/RecyclerViewItemAnimators

DividerItemDecoration

群号:423372824
源码下载
微信公众号:hongyangAndroid
(欢迎关注,第一时间推送博文信息)
1422600516_2905.jpg

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/dingxiaoyue/p/4924847.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/286654
推荐阅读
相关标签
  

闽ICP备14008679号