Android 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的使用代码:

<code class="language-java hljs  has-numbering">mRecyclerView = findView(R.id.id_recyclerview);
<span class="hljs-comment">//设置布局管理器</span>
mRecyclerView.setLayoutManager(layout);
<span class="hljs-comment">//设置adapter</span>
mRecyclerView.setAdapter(adapter)
<span class="hljs-comment">//设置Item增加、移除动画</span>
mRecyclerView.setItemAnimator(<span class="hljs-keyword">new</span> DefaultItemAnimator());
<span class="hljs-comment">//添加分割线</span>
mRecyclerView.addItemDecoration(<span class="hljs-keyword">new</span> DividerItemDecoration(
                getActivity(), DividerItemDecoration.HORIZONTAL_LIST));</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li></ul>

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

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

Just like ListView

  • Activity
<code class="language-java hljs  has-numbering"><span class="hljs-keyword">package</span> com.zhy.sample.demo_recyclerview;

<span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> android.os.Bundle;
<span class="hljs-keyword">import</span> android.support.v7.app.ActionBarActivity;
<span class="hljs-keyword">import</span> android.support.v7.widget.LinearLayoutManager;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView.ViewHolder;
<span class="hljs-keyword">import</span> android.view.LayoutInflater;
<span class="hljs-keyword">import</span> android.view.View;
<span class="hljs-keyword">import</span> android.view.ViewGroup;
<span class="hljs-keyword">import</span> android.widget.TextView;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomeActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ActionBarActivity</span>
{</span>

    <span class="hljs-keyword">private</span> RecyclerView mRecyclerView;
    <span class="hljs-keyword">private</span> List<String> mDatas;
    <span class="hljs-keyword">private</span> HomeAdapter mAdapter;

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span>(Bundle savedInstanceState)
    {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_recyclerview);

        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
        mRecyclerView.setLayoutManager(<span class="hljs-keyword">new</span> LinearLayoutManager(<span class="hljs-keyword">this</span>));
        mRecyclerView.setAdapter(mAdapter = <span class="hljs-keyword">new</span> HomeAdapter());

    }

    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">initData</span>()
    {
        mDatas = <span class="hljs-keyword">new</span> ArrayList<String>();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-string">'A'</span>; i < <span class="hljs-string">'z'</span>; i++)
        {
            mDatas.add(<span class="hljs-string">""</span> + (<span class="hljs-keyword">char</span>) i);
        }
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>
    {

        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> MyViewHolder <span class="hljs-title">onCreateViewHolder</span>(ViewGroup parent, <span class="hljs-keyword">int</span> viewType)
        {
            MyViewHolder holder = <span class="hljs-keyword">new</span> MyViewHolder(LayoutInflater.from(
                    HomeActivity.<span class="hljs-keyword">this</span>).inflate(R.layout.item_home, parent,
                    <span class="hljs-keyword">false</span>));
            <span class="hljs-keyword">return</span> holder;
        }

        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onBindViewHolder</span>(MyViewHolder holder, <span class="hljs-keyword">int</span> position)
        {
            holder.tv.setText(mDatas.get(position));
        }

        <span class="hljs-annotation">@Override</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getItemCount</span>()
        {
            <span class="hljs-keyword">return</span> mDatas.size();
        }

        class MyViewHolder extends ViewHolder
        {

            TextView tv;

            <span class="hljs-keyword">public</span> <span class="hljs-title">MyViewHolder</span>(View view)
            {
                <span class="hljs-keyword">super</span>(view);
                tv = (TextView) view.findViewById(R.id.id_num);
            }
        }
    }

}</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li></ul>
  • Activity的布局文件
<code class="language-xml hljs  has-numbering"><span class="hljs-tag"><<span class="hljs-title">RelativeLayout</span> <span class="hljs-attribute">xmlns:android</span>=<span class="hljs-value">"http://schemas.android.com/apk/res/android"</span>
    <span class="hljs-attribute">xmlns:tools</span>=<span class="hljs-value">"http://schemas.android.com/tools"</span>
    <span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"match_parent"</span>
    <span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"match_parent"</span> ></span>

    <span class="hljs-tag"><<span class="hljs-title">android.support.v7.widget.RecyclerView
</span>        <span class="hljs-attribute">android:id</span>=<span class="hljs-value">"@+id/id_recyclerview"</span>
         <span class="hljs-attribute">android:divider</span>=<span class="hljs-value">"#ffff0000"</span>
           <span class="hljs-attribute">android:dividerHeight</span>=<span class="hljs-value">"10dp"</span>
        <span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"match_parent"</span>
        <span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"match_parent"</span> /></span>

<span class="hljs-tag"></<span class="hljs-title">RelativeLayout</span>></span></code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li></ul>
  • Item的布局文件
<code class="language-xml hljs  has-numbering"><span class="hljs-pi"><?xml version="1.0" encoding="utf-8"?></span>
<span class="hljs-tag"><<span class="hljs-title">FrameLayout</span> <span class="hljs-attribute">xmlns:android</span>=<span class="hljs-value">"http://schemas.android.com/apk/res/android"</span>
    <span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"match_parent"</span>
    <span class="hljs-attribute">android:background</span>=<span class="hljs-value">"#44ff0000"</span>
    <span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"wrap_content"</span> ></span>

    <span class="hljs-tag"><<span class="hljs-title">TextView
</span>        <span class="hljs-attribute">android:id</span>=<span class="hljs-value">"@+id/id_num"</span>
        <span class="hljs-attribute">android:layout_width</span>=<span class="hljs-value">"match_parent"</span>
        <span class="hljs-attribute">android:layout_height</span>=<span class="hljs-value">"50dp"</span>
        <span class="hljs-attribute">android:gravity</span>=<span class="hljs-value">"center"</span>
        <span class="hljs-attribute">android:text</span>=<span class="hljs-value">"1"</span> /></span>
<span class="hljs-tag"></<span class="hljs-title">FrameLayout</span>></span></code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li></ul>

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

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

ItemDecoration

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

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ItemDecoration</span> {</span>

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDraw</span>(Canvas c, RecyclerView parent, State state) {
            onDraw(c, parent);
 }


<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDrawOver</span>(Canvas c, RecyclerView parent, State state) {
            onDrawOver(c, parent);
 }

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getItemOffsets</span>(Rect outRect, View view, RecyclerView parent, State state) {
            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
                    parent);
}

<span class="hljs-annotation">@Deprecated</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getItemOffsets</span>(Rect outRect, <span class="hljs-keyword">int</span> itemPosition, RecyclerView parent) {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
 }
</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li></ul>

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

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

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

<code class="language-java hljs  has-numbering">
<span class="hljs-keyword">package</span> com.zhy.sample.demo_recyclerview;

<span class="hljs-comment">/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * limitations under the License.
 */</span>

<span class="hljs-keyword">import</span> android.content.Context;
<span class="hljs-keyword">import</span> android.content.res.TypedArray;
<span class="hljs-keyword">import</span> android.graphics.Canvas;
<span class="hljs-keyword">import</span> android.graphics.Rect;
<span class="hljs-keyword">import</span> android.graphics.drawable.Drawable;
<span class="hljs-keyword">import</span> android.support.v7.widget.LinearLayoutManager;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView.State;
<span class="hljs-keyword">import</span> android.util.Log;
<span class="hljs-keyword">import</span> android.view.View;


<span class="hljs-javadoc">/**
 * This class is from the v7 samples of the Android SDK. It's not by me!
 * <p/>
 * See the license above for details.
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DividerItemDecoration</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">RecyclerView</span>.<span class="hljs-title">ItemDecoration</span> {</span>

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span>[] ATTRS = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[]{
            android.R.attr.listDivider
    };

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    <span class="hljs-keyword">private</span> Drawable mDivider;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> mOrientation;

    <span class="hljs-keyword">public</span> <span class="hljs-title">DividerItemDecoration</span>(Context context, <span class="hljs-keyword">int</span> orientation) {
        <span class="hljs-keyword">final</span> TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(<span class="hljs-number">0</span>);
        a.recycle();
        setOrientation(orientation);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setOrientation</span>(<span class="hljs-keyword">int</span> orientation) {
        <span class="hljs-keyword">if</span> (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalArgumentException(<span class="hljs-string">"invalid orientation"</span>);
        }
        mOrientation = orientation;
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDraw</span>(Canvas c, RecyclerView parent) {
        Log.v(<span class="hljs-string">"recyclerview - itemdecoration"</span>, <span class="hljs-string">"onDraw()"</span>);

        <span class="hljs-keyword">if</span> (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } <span class="hljs-keyword">else</span> {
            drawHorizontal(c, parent);
        }

    }


    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawVertical</span>(Canvas c, RecyclerView parent) {
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> left = parent.getPaddingLeft();
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> right = parent.getWidth() - parent.getPaddingRight();

        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childCount = parent.getChildCount();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < childCount; i++) {
            <span class="hljs-keyword">final</span> View child = parent.getChildAt(i);
            android.support.v7.widget.RecyclerView v = <span class="hljs-keyword">new</span> android.support.v7.widget.RecyclerView(parent.getContext());
            <span class="hljs-keyword">final</span> RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> top = child.getBottom() + params.bottomMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawHorizontal</span>(Canvas c, RecyclerView parent) {
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> top = parent.getPaddingTop();
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> bottom = parent.getHeight() - parent.getPaddingBottom();

        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childCount = parent.getChildCount();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < childCount; i++) {
            <span class="hljs-keyword">final</span> View child = parent.getChildAt(i);
            <span class="hljs-keyword">final</span> RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> left = child.getRight() + params.rightMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getItemOffsets</span>(Rect outRect, <span class="hljs-keyword">int</span> itemPosition, RecyclerView parent) {
        <span class="hljs-keyword">if</span> (mOrientation == VERTICAL_LIST) {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mDivider.getIntrinsicHeight());
        } <span class="hljs-keyword">else</span> {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mDivider.getIntrinsicWidth(), <span class="hljs-number">0</span>);
        }
    }
}</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li><li>90</li><li>91</li><li>92</li><li>93</li><li>94</li><li>95</li><li>96</li><li>97</li><li>98</li><li>99</li><li>100</li><li>101</li><li>102</li><li>103</li><li>104</li><li>105</li><li>106</li><li>107</li><li>108</li><li>109</li><li>110</li></ul>

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

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

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

<code class="language-java hljs  has-numbering">mRecyclerView.addItemDecoration(<span class="hljs-keyword">new</span> DividerItemDecoration(<span class="hljs-keyword">this</span>,
DividerItemDecoration.VERTICAL_LIST));</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

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

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

<code class="language-xml hljs  has-numbering"> <span class="hljs-comment"><!-- Application theme. --></span>
    <span class="hljs-tag"><<span class="hljs-title">style</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"AppTheme"</span> <span class="hljs-attribute">parent</span>=<span class="hljs-value">"AppBaseTheme"</span>></span><span class="css">
      <<span class="hljs-tag">item</span> <span class="hljs-tag">name</span>="<span class="hljs-tag">android</span><span class="hljs-pseudo">:listDivider"</span>><span class="hljs-at_rule">@<span class="hljs-keyword">drawable/divider_bg</item></span>  
    </span></span><span class="hljs-tag"></<span class="hljs-title">style</span>></span></code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li></ul>

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

<code class="language-java hljs  has-numbering"><?xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"utf-8"</span>?>
<shape xmlns:android=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span>
    android:shape=<span class="hljs-string">"rectangle"</span> >

    <gradient
        android:centerColor=<span class="hljs-string">"#ff00ff00"</span>
        android:endColor=<span class="hljs-string">"#ff0000ff"</span>
        android:startColor=<span class="hljs-string">"#ffff0000"</span>
        android:type=<span class="hljs-string">"linear"</span> />
    <size android:height=<span class="hljs-string">"4dp"</span>/>

</shape></code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>

现在的样子是:

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

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

LayoutManager

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

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

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

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

  • GridLayoutManager

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

<code class="language-java hljs  has-numbering"><span class="hljs-comment">//mRecyclerView.setLayoutManager(new LinearLayoutManager(this));</span>
        mRecyclerView.setLayoutManager(<span class="hljs-keyword">new</span> GridLayoutManager(<span class="hljs-keyword">this</span>,<span class="hljs-number">4</span>));</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

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

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

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> left = parent.getPaddingLeft();
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> right = parent.getWidth() - parent.getPaddingRight();</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

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

针对上述,我们编写了DividerGridItemDecoration

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">package</span> com.zhy.sample.demo_recyclerview;

<span class="hljs-keyword">import</span> android.content.Context;
<span class="hljs-keyword">import</span> android.content.res.TypedArray;
<span class="hljs-keyword">import</span> android.graphics.Canvas;
<span class="hljs-keyword">import</span> android.graphics.Rect;
<span class="hljs-keyword">import</span> android.graphics.drawable.Drawable;
<span class="hljs-keyword">import</span> android.support.v7.widget.GridLayoutManager;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView.LayoutManager;
<span class="hljs-keyword">import</span> android.support.v7.widget.RecyclerView.State;
<span class="hljs-keyword">import</span> android.support.v7.widget.StaggeredGridLayoutManager;
<span class="hljs-keyword">import</span> android.view.View;

<span class="hljs-javadoc">/**
 * 
 *<span class="hljs-javadoctag"> @author</span> zhy
 * 
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DividerGridItemDecoration</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">RecyclerView</span>.<span class="hljs-title">ItemDecoration</span>
{</span>

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span>[] ATTRS = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[] { android.R.attr.listDivider };
    <span class="hljs-keyword">private</span> Drawable mDivider;

    <span class="hljs-keyword">public</span> <span class="hljs-title">DividerGridItemDecoration</span>(Context context)
    {
        <span class="hljs-keyword">final</span> TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(<span class="hljs-number">0</span>);
        a.recycle();
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDraw</span>(Canvas c, RecyclerView parent, State state)
    {

        drawHorizontal(c, parent);
        drawVertical(c, parent);

    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getSpanCount</span>(RecyclerView parent)
    {
        <span class="hljs-comment">// 列数</span>
        <span class="hljs-keyword">int</span> spanCount = -<span class="hljs-number">1</span>;
        LayoutManager layoutManager = parent.getLayoutManager();
        <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> GridLayoutManager)
        {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> StaggeredGridLayoutManager)
        {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        <span class="hljs-keyword">return</span> spanCount;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawHorizontal</span>(Canvas c, RecyclerView parent)
    {
        <span class="hljs-keyword">int</span> childCount = parent.getChildCount();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < childCount; i++)
        {
            <span class="hljs-keyword">final</span> View child = parent.getChildAt(i);
            <span class="hljs-keyword">final</span> RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> left = child.getLeft() - params.leftMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> right = child.getRight() + params.rightMargin
                    + mDivider.getIntrinsicWidth();
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> top = child.getBottom() + params.bottomMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawVertical</span>(Canvas c, RecyclerView parent)
    {
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childCount = parent.getChildCount();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < childCount; i++)
        {
            <span class="hljs-keyword">final</span> View child = parent.getChildAt(i);

            <span class="hljs-keyword">final</span> RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> top = child.getTop() - params.topMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> bottom = child.getBottom() + params.bottomMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> left = child.getRight() + params.rightMargin;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> right = left + mDivider.getIntrinsicWidth();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isLastColum</span>(RecyclerView parent, <span class="hljs-keyword">int</span> pos, <span class="hljs-keyword">int</span> spanCount,
            <span class="hljs-keyword">int</span> childCount)
    {
        LayoutManager layoutManager = parent.getLayoutManager();
        <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> GridLayoutManager)
        {
            <span class="hljs-keyword">if</span> ((pos + <span class="hljs-number">1</span>) % spanCount == <span class="hljs-number">0</span>)<span class="hljs-comment">// 如果是最后一列,则不需要绘制右边</span>
            {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> StaggeredGridLayoutManager)
        {
            <span class="hljs-keyword">int</span> orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            <span class="hljs-keyword">if</span> (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                <span class="hljs-keyword">if</span> ((pos + <span class="hljs-number">1</span>) % spanCount == <span class="hljs-number">0</span>)<span class="hljs-comment">// 如果是最后一列,则不需要绘制右边</span>
                {
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
                }
            } <span class="hljs-keyword">else</span>
            {
                childCount = childCount - childCount % spanCount;
                <span class="hljs-keyword">if</span> (pos >= childCount)<span class="hljs-comment">// 如果是最后一列,则不需要绘制右边</span>
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isLastRaw</span>(RecyclerView parent, <span class="hljs-keyword">int</span> pos, <span class="hljs-keyword">int</span> spanCount,
            <span class="hljs-keyword">int</span> childCount)
    {
        LayoutManager layoutManager = parent.getLayoutManager();
        <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> GridLayoutManager)
        {
            childCount = childCount - childCount % spanCount;
            <span class="hljs-keyword">if</span> (pos >= childCount)<span class="hljs-comment">// 如果是最后一行,则不需要绘制底部</span>
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (layoutManager <span class="hljs-keyword">instanceof</span> StaggeredGridLayoutManager)
        {
            <span class="hljs-keyword">int</span> orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            <span class="hljs-comment">// StaggeredGridLayoutManager 且纵向滚动</span>
            <span class="hljs-keyword">if</span> (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                childCount = childCount - childCount % spanCount;
                <span class="hljs-comment">// 如果是最后一行,则不需要绘制底部</span>
                <span class="hljs-keyword">if</span> (pos >= childCount)
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            } <span class="hljs-keyword">else</span>
            <span class="hljs-comment">// StaggeredGridLayoutManager 且横向滚动</span>
            {
                <span class="hljs-comment">// 如果是最后一行,则不需要绘制底部</span>
                <span class="hljs-keyword">if</span> ((pos + <span class="hljs-number">1</span>) % spanCount == <span class="hljs-number">0</span>)
                {
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
                }
            }
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getItemOffsets</span>(Rect outRect, <span class="hljs-keyword">int</span> itemPosition,
            RecyclerView parent)
    {
        <span class="hljs-keyword">int</span> spanCount = getSpanCount(parent);
        <span class="hljs-keyword">int</span> childCount = parent.getAdapter().getItemCount();
        <span class="hljs-keyword">if</span> (isLastRaw(parent, itemPosition, spanCount, childCount))<span class="hljs-comment">// 如果是最后一行,则不需要绘制底部</span>
        {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mDivider.getIntrinsicWidth(), <span class="hljs-number">0</span>);
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (isLastColum(parent, itemPosition, spanCount, childCount))<span class="hljs-comment">// 如果是最后一列,则不需要绘制右边</span>
        {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mDivider.getIntrinsicHeight());
        } <span class="hljs-keyword">else</span>
        {
            outRect.set(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mDivider.getIntrinsicWidth(),
                    mDivider.getIntrinsicHeight());
        }
    }
}
</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li><li>90</li><li>91</li><li>92</li><li>93</li><li>94</li><li>95</li><li>96</li><li>97</li><li>98</li><li>99</li><li>100</li><li>101</li><li>102</li><li>103</li><li>104</li><li>105</li><li>106</li><li>107</li><li>108</li><li>109</li><li>110</li><li>111</li><li>112</li><li>113</li><li>114</li><li>115</li><li>116</li><li>117</li><li>118</li><li>119</li><li>120</li><li>121</li><li>122</li><li>123</li><li>124</li><li>125</li><li>126</li><li>127</li><li>128</li><li>129</li><li>130</li><li>131</li><li>132</li><li>133</li><li>134</li><li>135</li><li>136</li><li>137</li><li>138</li><li>139</li><li>140</li><li>141</li><li>142</li><li>143</li><li>144</li><li>145</li><li>146</li><li>147</li><li>148</li><li>149</li><li>150</li><li>151</li><li>152</li><li>153</li><li>154</li><li>155</li><li>156</li><li>157</li><li>158</li><li>159</li><li>160</li><li>161</li><li>162</li><li>163</li><li>164</li><li>165</li><li>166</li><li>167</li><li>168</li><li>169</li><li>170</li><li>171</li><li>172</li><li>173</li><li>174</li><li>175</li><li>176</li><li>177</li><li>178</li></ul>

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

最后的效果是:

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

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

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

  • StaggeredGridLayoutManager

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

<code class="language-java hljs  has-numbering"><span class="hljs-comment">// mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));</span>
        mRecyclerView.setLayoutManager(<span class="hljs-keyword">new</span> StaggeredGridLayoutManager(<span class="hljs-number">4</span>,        StaggeredGridLayoutManager.VERTICAL));</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

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

<code class="language-java hljs  has-numbering">mRecyclerView.setLayoutManager(<span class="hljs-keyword">new</span> StaggeredGridLayoutManager(<span class="hljs-number">4</span>,
        StaggeredGridLayoutManager.HORIZONTAL));</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

那么效果为:

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

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

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

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

ItemAnimator

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

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

<code class="language-java hljs  has-numbering"><span class="hljs-comment">// 设置item动画</span>
mRecyclerView.setItemAnimator(<span class="hljs-keyword">new</span> DefaultItemAnimator());</code><ul class="pre-numbering"><li>1</li><li>2</li></ul>

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

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

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

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addData</span>(<span class="hljs-keyword">int</span> position) {
        mDatas.add(position, <span class="hljs-string">"Insert One"</span>);
        notifyItemInserted(position);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">removeData</span>(<span class="hljs-keyword">int</span> position) {
            mDatas.remove(position);
        notifyItemRemoved(position);
    }</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

Activity中点击MenuItem触发:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onCreateOptionsMenu</span>(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">super</span>.onCreateOptionsMenu(menu);
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onOptionsItemSelected</span>(MenuItem item)
    {
        <span class="hljs-keyword">switch</span> (item.getItemId())
        {
        <span class="hljs-keyword">case</span> R.id.id_action_add:
            mAdapter.addData(<span class="hljs-number">1</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> R.id.id_action_delete:
            mAdapter.removeData(<span class="hljs-number">1</span>);
            <span class="hljs-keyword">break</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li></ul>

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

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

Click and LongClick

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

那么代码也比较简单:

<code class="language-java hljs  has-numbering">class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>
{

<span class="hljs-comment">//...</span>
    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">OnItemClickLitener</span>
    {</span>
        <span class="hljs-keyword">void</span> onItemClick(View view, <span class="hljs-keyword">int</span> position);
        <span class="hljs-keyword">void</span> onItemLongClick(View view , <span class="hljs-keyword">int</span> position);
    }

    <span class="hljs-keyword">private</span> OnItemClickLitener mOnItemClickLitener;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setOnItemClickLitener</span>(OnItemClickLitener mOnItemClickLitener)
    {
        <span class="hljs-keyword">this</span>.mOnItemClickLitener = mOnItemClickLitener;
    }

    <span class="hljs-annotation">@Override</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onBindViewHolder</span>(<span class="hljs-keyword">final</span> MyViewHolder holder, <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> position)
    {
        holder.tv.setText(mDatas.get(position));

        <span class="hljs-comment">// 如果设置了回调,则设置点击事件</span>
        <span class="hljs-keyword">if</span> (mOnItemClickLitener != <span class="hljs-keyword">null</span>)
        {
            holder.itemView.setOnClickListener(<span class="hljs-keyword">new</span> OnClickListener()
            {
                <span class="hljs-annotation">@Override</span>
                <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onClick</span>(View v)
                {
                    <span class="hljs-keyword">int</span> pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemClick(holder.itemView, pos);
                }
            });

            holder.itemView.setOnLongClickListener(<span class="hljs-keyword">new</span> OnLongClickListener()
            {
                <span class="hljs-annotation">@Override</span>
                <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">onLongClick</span>(View v)
                {
                    <span class="hljs-keyword">int</span> pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
                }
            });
        }
    }
<span class="hljs-comment">//...</span>
}
</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li></ul>

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

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

<code class="language-xml hljs  has-numbering"><span class="hljs-pi"><?xml version="1.0" encoding="utf-8"?></span>
<span class="hljs-tag"><<span class="hljs-title">selector</span> <span class="hljs-attribute">xmlns:android</span>=<span class="hljs-value">"http://schemas.android.com/apk/res/android"</span> ></span>
    <span class="hljs-tag"><<span class="hljs-title">item</span> <span class="hljs-attribute">android:state_pressed</span>=<span class="hljs-value">"true"</span> <span class="hljs-attribute">android:drawable</span>=<span class="hljs-value">"@color/color_item_press"</span>></span><span class="hljs-tag"></<span class="hljs-title">item</span>></span>
    <span class="hljs-tag"><<span class="hljs-title">item</span> <span class="hljs-attribute">android:drawable</span>=<span class="hljs-value">"@color/color_item_normal"</span>></span><span class="hljs-tag"></<span class="hljs-title">item</span>></span>
<span class="hljs-tag"></<span class="hljs-title">selector</span>></span>
</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li></ul>

Activity中去设置监听:

<code class="language-java hljs  has-numbering">
        mAdapter.setOnItemClickLitener(<span class="hljs-keyword">new</span> OnItemClickLitener()
        {

            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onItemClick</span>(View view, <span class="hljs-keyword">int</span> position)
            {
                Toast.makeText(HomeActivity.<span class="hljs-keyword">this</span>, position + <span class="hljs-string">" click"</span>,
                        Toast.LENGTH_SHORT).show();
            }

            <span class="hljs-annotation">@Override</span>
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onItemLongClick</span>(View view, <span class="hljs-keyword">int</span> position)
            {
                Toast.makeText(HomeActivity.<span class="hljs-keyword">this</span>, position + <span class="hljs-string">" long click"</span>,
                        Toast.LENGTH_SHORT).show();
                        mAdapter.removeData(position);
            }
        });
</code><ul class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li></ul>

测试效果:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值