Android RecyclerView 使用完全解析 體驗(yàn)藝術(shù)般的控件

轉(zhuǎn)載請(qǐng)標(biāo)明出處:
http://blog.csdn.net/lmj623565791/article/details/45059587;
本文出自:【張鴻洋的博客】

概述

RecyclerView出現(xiàn)已經(jīng)有一段時(shí)間了,相信大家肯定不陌生了,大家可以通過(guò)導(dǎo)入support-v7對(duì)其進(jìn)行使用。
據(jù)官方的介紹,該控件用于在有限的窗口中展示大量數(shù)據(jù)集,其實(shí)這樣功能的控件我們并不陌生,例如:ListView、GridView。

那么有了ListView、GridView為什么還需要RecyclerView這樣的控件呢?整體上看RecyclerView架構(gòu),提供了一種插拔式的體驗(yàn),高度的解耦,異常的靈活,通過(guò)設(shè)置它提供的不同LayoutManager,ItemDecoration , ItemAnimator實(shí)現(xiàn)令人瞠目的效果。

  • 你想要控制其顯示的方式,請(qǐng)通過(guò)布局管理器LayoutManager
  • 你想要控制Item間的間隔(可繪制),請(qǐng)通過(guò)ItemDecoration
  • 你想要控制Item增刪的動(dòng)畫,請(qǐng)通過(guò)ItemAnimator
  • 你想要控制點(diǎn)擊、長(zhǎng)按事件,請(qǐng)自己寫(擦,這點(diǎn)尼瑪。)

基本使用

鑒于我們對(duì)于ListView的使用特別的熟悉,對(duì)比下RecyclerView的使用代碼:

mRecyclerView = findView(R.id.id_recyclerview);
//設(shè)置布局管理器
mRecyclerView.setLayoutManager(layout);
//設(shè)置adapter
mRecyclerView.setAdapter(adapter)
//設(shè)置Item增加、移除動(dòng)畫
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//添加分割線
mRecyclerView.addItemDecoration(new DividerItemDecoration(
                getActivity(), DividerItemDecoration.HORIZONTAL_LIST));

ok,相比較于ListView的代碼,ListView可能只需要去設(shè)置一個(gè)adapter就能正常使用了。而RecyclerView基本需要上面一系列的步驟,那么為什么會(huì)添加這么多的步驟呢?

那么就必須解釋下RecyclerView的這個(gè)名字了,從它類名上看,RecyclerView代表的意義是,我只管Recycler View,也就是說(shuō)RecyclerView只管回收與復(fù)用View,其他的你可以自己去設(shè)置??梢钥闯銎涓叨鹊慕怦?,給予你充分的定制自由(所以你才可以輕松的通過(guò)這個(gè)控件實(shí)現(xiàn)ListView,GirdView,瀑布流等效果)。

Just like ListView

  • Activity
package com.zhy.sample.demo_recyclerview;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class HomeActivity extends ActionBarActivity
{

    private RecyclerView mRecyclerView;
    private List<String> mDatas;
    private HomeAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_recyclerview);

        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter = new HomeAdapter());

    }

    protected void initData()
    {
        mDatas = new ArrayList<String>();
        for (int i = 'A'; i < 'z'; i++)
        {
            mDatas.add("" + (char) i);
        }
    }

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

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    HomeActivity.this).inflate(R.layout.item_home, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position)
        {
            holder.tv.setText(mDatas.get(position));
        }

        @Override
        public int getItemCount()
        {
            return mDatas.size();
        }

        class MyViewHolder extends ViewHolder
        {

            TextView tv;

            public MyViewHolder(View view)
            {
                super(view);
                tv = (TextView) view.findViewById(R.id.id_num);
            }
        }
    }

}
  • Activity的布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/id_recyclerview"
         android:divider="#ffff0000"
           android:dividerHeight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
  • Item的布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#44ff0000"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/id_num"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="1" />
</FrameLayout>

這么看起來(lái)用法與ListView的代碼基本一致哈~~
看下效果圖:


效果圖

看起來(lái)好丑,Item間應(yīng)該有個(gè)分割線,當(dāng)你去找時(shí),你會(huì)發(fā)現(xiàn)RecyclerView并沒(méi)有支持divider這樣的屬性。那么怎么辦,你可以給Item的布局去設(shè)置margin,當(dāng)然了這種方式不夠優(yōu)雅,我們文章開始說(shuō)了,我們可以自由的去定制它,當(dāng)然我們的分割線也是可以定制的。

ItemDecoration

我們可以通過(guò)該方法添加分割線:
mRecyclerView.addItemDecoration();
該方法的參數(shù)為RecyclerView.ItemDecoration,該類為抽象類,官方目前并沒(méi)有提供默認(rèn)的實(shí)現(xiàn)類(我覺(jué)得最好能提供幾個(gè))。
該類的源碼:

public static abstract class ItemDecoration {

public void onDraw(Canvas c, RecyclerView parent, State state) {
            onDraw(c, parent);
 }


public void onDrawOver(Canvas c, RecyclerView parent, State state) {
            onDrawOver(c, parent);
 }

public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
                    parent);
}

@Deprecated
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            outRect.set(0, 0, 0, 0);
 }

當(dāng)我們調(diào)用mRecyclerView.addItemDecoration()方法添加decoration的時(shí)候,RecyclerView在繪制的時(shí)候,去會(huì)繪制decorator,即調(diào)用該類的onDraw和onDrawOver方法,

  • onDraw方法先于drawChildren
  • onDrawOver在drawChildren之后,一般我們選擇復(fù)寫其中一個(gè)即可。
  • getItemOffsets 可以通過(guò)outRect.set()為每個(gè)Item設(shè)置一定的偏移量,主要用于繪制Decorator。

接下來(lái)我們看一個(gè)RecyclerView.ItemDecoration的實(shí)現(xiàn)類,該類很好的實(shí)現(xiàn)了RecyclerView添加分割線(當(dāng)使用LayoutManager為L(zhǎng)inearLayoutManager時(shí))。
該類參考自:DividerItemDecoration

package com.zhy.sample.demo_recyclerview;

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * limitations under the License.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.State;
import android.util.Log;
import android.view.View;


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

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        Log.v("recyclerview - itemdecoration", "onDraw()");

        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }

    }


    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

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

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

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

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

該實(shí)現(xiàn)類可以看到通過(guò)讀取系統(tǒng)主題中的 android.R.attr.listDivider作為Item間的分割線,并且支持橫向和縱向。如果你不清楚它是怎么做到的讀取系統(tǒng)的屬性用于自身,請(qǐng)參考我的另一篇博文:Android 深入理解Android中的自定義屬性

獲取到listDivider以后,該屬性的值是個(gè)Drawable,在getItemOffsets中,outRect去設(shè)置了繪制的范圍。onDraw中實(shí)現(xiàn)了真正的繪制。

我們?cè)谠瓉?lái)的代碼中添加一句:

mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL_LIST));

ok,現(xiàn)在再運(yùn)行,就可以看到分割線的效果了。


有分割線的效果圖

該分割線是系統(tǒng)默認(rèn)的,你可以在theme.xml中找到該屬性的使用情況。那么,使用系統(tǒng)的listDivider有什么好處呢?就是方便我們?nèi)ルS意的改變,該屬性我們可以直接聲明在:

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

然后自己寫個(gè)drawable即可,下面我們換一種分隔符:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />
    <size android:height="4dp"/>
</shape>

現(xiàn)在的樣子是:
加了效果的圖片

當(dāng)然了,你可以根據(jù)自己的需求,去隨意的繪制,反正是畫出來(lái)的,隨便玩~~

ok,看到這,你可能覺(jué)得,這玩意真尼瑪麻煩,完全不能比擬的心愛(ài)的ListView。那么繼續(xù)看。

LayoutManager

好了,上面實(shí)現(xiàn)了類似ListView樣子的Demo,通過(guò)使用其默認(rèn)的LinearLayoutManager。

RecyclerView.LayoutManager吧,這是一個(gè)抽象類,好在系統(tǒng)提供了3個(gè)實(shí)現(xiàn)類:

  1. LinearLayoutManager 現(xiàn)行管理器,支持橫向、縱向。
  2. GridLayoutManager 網(wǎng)格布局管理器
  3. StaggeredGridLayoutManager 瀑布就式布局管理器

上面我們已經(jīng)初步體驗(yàn)了下LinearLayoutManager,接下來(lái)看GridLayoutManager。

  • GridLayoutManager

我們嘗試去實(shí)現(xiàn)類似GridView,秒秒鐘的事情:
//mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
只需要修改LayoutManager即可,還是很nice的。

當(dāng)然了,改為GridLayoutManager以后,對(duì)于分割線,前面的DividerItemDecoration就不適用了,主要是因?yàn)樗诶L制的時(shí)候,比如水平線,針對(duì)每個(gè)child的取值為:
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
因?yàn)槊總€(gè)Item一行,這樣是沒(méi)問(wèn)題的。而GridLayoutManager時(shí),一行有多個(gè)childItem,這樣就多次繪制了,并且GridLayoutManager時(shí),Item如果為最后一列(則右邊無(wú)間隔線)或者為最后一行(底部無(wú)分割線)。

針對(duì)上述,我們編寫了DividerGridItemDecoration。

package com.zhy.sample.demo_recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.RecyclerView.State;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

/**
 * 
 * @author zhy
 * 
 */
public class DividerGridItemDecoration extends RecyclerView.ItemDecoration
{

    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };
    private Drawable mDivider;

    public DividerGridItemDecoration(Context context)
    {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, State state)
    {

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

    }

    private int getSpanCount(RecyclerView parent)
    {
        // 列數(shù)
        int spanCount = -1;
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }

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

    public void drawVertical(Canvas c, RecyclerView parent)
    {
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getTop() - params.topMargin;
            final int bottom = child.getBottom() + params.bottomMargin;
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();

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

    private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
            int childCount)
    {
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {
            if ((pos + 1) % spanCount == 0)// 如果是最后一列,則不需要繪制右邊
            {
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            if (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                if ((pos + 1) % spanCount == 0)// 如果是最后一列,則不需要繪制右邊
                {
                    return true;
                }
            } else
            {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一列,則不需要繪制右邊
                    return true;
            }
        }
        return false;
    }

    private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
            int childCount)
    {
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager)
        {
            childCount = childCount - childCount % spanCount;
            if (pos >= childCount)// 如果是最后一行,則不需要繪制底部
                return true;
        } else if (layoutManager instanceof StaggeredGridLayoutManager)
        {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            // StaggeredGridLayoutManager 且縱向滾動(dòng)
            if (orientation == StaggeredGridLayoutManager.VERTICAL)
            {
                childCount = childCount - childCount % spanCount;
                // 如果是最后一行,則不需要繪制底部
                if (pos >= childCount)
                    return true;
            } else
            // StaggeredGridLayoutManager 且橫向滾動(dòng)
            {
                // 如果是最后一行,則不需要繪制底部
                if ((pos + 1) % spanCount == 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
            RecyclerView parent)
    {
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();
        if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,則不需要繪制底部
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,則不需要繪制右邊
        {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                    mDivider.getIntrinsicHeight());
        }
    }
}

主要在getItemOffsets方法中,去判斷如果是最后一行,則不需要繪制底部;如果是最后一列,則不需要繪制右邊,整個(gè)判斷也考慮到了StaggeredGridLayoutManager的橫向和縱向,所以稍稍有些復(fù)雜。最重要還是去理解,如何繪制什么的不重要。一般如果僅僅是希望有空隙,還是去設(shè)置item的margin方便。

最后的效果是:

ok,看到這,你可能還覺(jué)得RecyclerView不夠強(qiáng)大?

但是如果我們有這么個(gè)需求,縱屏的時(shí)候顯示為L(zhǎng)istView,橫屏的時(shí)候顯示兩列的GridView,我們RecyclerView可以輕松搞定,而如果使用ListView去實(shí)現(xiàn)還是需要點(diǎn)功夫的~~~

當(dāng)然了,這只是皮毛,下面讓你心服口服。

  • StaggeredGridLayoutManager

瀑布流式的布局,其實(shí)他可以實(shí)現(xiàn)GridLayoutManager一樣的功能,僅僅按照下列代碼:
// mRecyclerView.setLayoutManager(new GridLayoutManager(this,4)); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
這兩種寫法顯示的效果是一致的,但是注意StaggeredGridLayoutManager構(gòu)造的第二個(gè)參數(shù)傳一個(gè)orientation,如果傳入的是StaggeredGridLayoutManager.VERTICAL代表有多少列;那么傳入的如果是StaggeredGridLayoutManager.HORIZONTAL就代表有多少行,比如本例如果改為:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL));
那么效果為:


可以看到,固定為4行,變成了左右滑動(dòng)。有一點(diǎn)需要注意,如果是橫向的時(shí)候,item的寬度需要注意去設(shè)置,畢竟橫向的寬度沒(méi)有約束了,應(yīng)為控件可以橫向滾動(dòng)了。
如果你需要一樣橫向滾動(dòng)的GridView,那么恭喜你。

ok,接下來(lái)準(zhǔn)備看大招,如果讓你去實(shí)現(xiàn)個(gè)瀑布流,最起碼不是那么隨意就可以實(shí)現(xiàn)的吧?但是,如果使用RecyclerView,分分鐘的事。
那么如何實(shí)現(xiàn)?其實(shí)你什么都不用做,只要使用StaggeredGridLayoutManager我們就已經(jīng)實(shí)現(xiàn)了,只是上面的item布局我們使用了固定的高度,下面我們僅僅在適配器的onBindViewHolder方法中為我們的item設(shè)置個(gè)隨機(jī)的高度(代碼就不貼了,最后會(huì)給出源碼下載地址),看看效果圖:


是不是棒棒噠,通過(guò)RecyclerView去實(shí)現(xiàn)ListView、GridView、瀑布流的效果基本上沒(méi)有什么區(qū)別,而且可以僅僅通過(guò)設(shè)置不同的LayoutManager即可實(shí)現(xiàn)。

還有更nice的地方,就在于item增加、刪除的動(dòng)畫也是可配置的。接下來(lái)看一下ItemAnimator。

ItemAnimator

ItemAnimator也是一個(gè)抽象類,好在系統(tǒng)為我們提供了一種默認(rèn)的實(shí)現(xiàn)類,期待系統(tǒng)多 添加些默認(rèn)的實(shí)現(xiàn)。
借助默認(rèn)的實(shí)現(xiàn),當(dāng)Item添加和移除的時(shí)候,添加動(dòng)畫效果很簡(jiǎn)單:
// 設(shè)置item動(dòng)畫
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
系統(tǒng)為我們提供了一個(gè)默認(rèn)的實(shí)現(xiàn),我們?yōu)槲覀兊钠俨剂魈砑右陨弦恍写a,效果為:


如果是GridLayoutManager呢?動(dòng)畫效果為:

注意,這里更新數(shù)據(jù)集不是用adapter.notifyDataSetChanged()而是
notifyItemInserted(position)notifyItemRemoved(position)
否則沒(méi)有動(dòng)畫效果。
上述為adapter中添加了兩個(gè)方法:

public void addData(int position) {
        mDatas.add(position, "Insert One");
        notifyItemInserted(position);
    }
 public void removeData(int position) {
            mDatas.remove(position);
        notifyItemRemoved(position);
    }

Activity中點(diǎn)擊MenuItem觸發(fā):

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.id_action_add:
            mAdapter.addData(1);
            break;
        case R.id.id_action_delete:
            mAdapter.removeData(1);
            break;
        }
        return true;
    }

好了,到這我對(duì)這個(gè)控件已經(jīng)不是一般的喜歡了~~~

當(dāng)然了只提供了一種動(dòng)畫,那么我們肯定可以去自定義各種nice的動(dòng)畫效果。
高興的是,github上已經(jīng)有很多類似的項(xiàng)目了,這里我們直接引用下:RecyclerViewItemAnimators,大家自己下載查看。
提供了SlideInOutLeftItemAnimator,SlideInOutRightItemAnimator,
SlideInOutTopItemAnimator,SlideInOutBottomItemAnimator等動(dòng)畫效果。

Click and LongClick

不過(guò)一個(gè)挺郁悶的地方就是,系統(tǒng)沒(méi)有提供ClickListener和LongClickListener。
不過(guò)我們也可以自己去添加,只是會(huì)多了些代碼而已。
實(shí)現(xiàn)的方式比較多,你可以通過(guò)mRecyclerView.addOnItemTouchListener去監(jiān)聽(tīng)然后去判斷手勢(shì),
當(dāng)然你也可以通過(guò)adapter中自己去提供回調(diào),這里我們選擇后者,前者的方式,大家有興趣自己去實(shí)現(xiàn)。

那么代碼也比較簡(jiǎn)單:

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

//...
    public interface OnItemClickLitener
    {
        void onItemClick(View view, int position);
        void onItemLongClick(View view , int position);
    }

    private OnItemClickLitener mOnItemClickLitener;

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener)
    {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position)
    {
        holder.tv.setText(mDatas.get(position));

        // 如果設(shè)置了回調(diào),則設(shè)置點(diǎn)擊事件
        if (mOnItemClickLitener != null)
        {
            holder.itemView.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemClick(holder.itemView, pos);
                }
            });

            holder.itemView.setOnLongClickListener(new OnLongClickListener()
            {
                @Override
                public boolean onLongClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                    return false;
                }
            });
        }
    }
//...
}

最后別忘了給item添加一個(gè)drawable:

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

Activity中去設(shè)置監(jiān)聽(tīng):

mAdapter.setOnItemClickLitener(new OnItemClickLitener()
        {

            @Override
            public void onItemClick(View view, int position)
            {
                Toast.makeText(HomeActivity.this, position + " click",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position)
            {
                Toast.makeText(HomeActivity.this, position + " long click",
                        Toast.LENGTH_SHORT).show();
                        mAdapter.removeData(position);
            }
        });

ok,到此我們基本介紹了RecylerView常見(jiàn)用法,包含了:

  • 系統(tǒng)提供了幾種LayoutManager的使用;
  • 如何通過(guò)自定義ItemDecoration去設(shè)置分割線,或者一些你想作為分隔的drawable,注意這里
    巧妙的使用了系統(tǒng)的listDivider屬性,你可以嘗試添加使用divider和dividerHeight屬性。
  • 如何使用ItemAnimator為RecylerView去添加Item移除、添加的動(dòng)畫效果。
  • 介紹了如何添加ItemClickListener與ItemLongClickListener。

可以看到RecyclerView可以實(shí)現(xiàn):

整個(gè)體驗(yàn)下來(lái),感覺(jué)這種插拔式的設(shè)計(jì)太棒了,如果系統(tǒng)再能提供一些常用的分隔符,多添加些動(dòng)畫效果就更好了。

通過(guò)簡(jiǎn)單改變下LayoutManager,就可以產(chǎn)生不同的效果,那么我們可以根據(jù)手機(jī)屏幕的寬度去動(dòng)態(tài)設(shè)置LayoutManager,屏幕寬度一般的,顯示為L(zhǎng)istView;寬度稍大的顯示兩列的GridView或者瀑布流(或者橫縱屏幕切換時(shí)變化,有點(diǎn)意思);顯示的列數(shù)和寬度成正比。甚至某些特殊屏幕,讓其橫向滑動(dòng)~再選擇一個(gè)nice的動(dòng)畫效果,相信這種插件式的編碼體驗(yàn)一定會(huì)讓你迅速愛(ài)上RecyclerView。

參考資料

Android 自定義RecyclerView 實(shí)現(xiàn)真正的Gallery效果

A First Glance at Android’s RecyclerView

https://github.com/gabrielemariotti/RecyclerViewItemAnimators

DividerItemDecoration

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容