崇拜下鴻洋大神,原文地址:http://blog.csdn.net/lmj623565791/article/details/45059587java
RecyclerView出現已經有一段時間了,相信你們確定不陌生了,你們能夠經過導入support-v7對其進行使用。
據官方的介紹,該控件用於在有限的窗口中展現大量數據集,其實這樣功能的控件咱們並不陌生,例如:ListView、GridView。android
那麼有了ListView、GridView爲何還須要RecyclerView這樣的控件呢?總體上看RecyclerView架構,提供了一種插拔式的體驗,高度的解耦,異常的靈活,經過設置它提供的不一樣LayoutManager,ItemDecoration , ItemAnimator實現使人瞠目的效果。git
鑑於咱們對於ListView的使用特別的熟悉,對比下RecyclerView的使用代碼:github
mRecyclerView = findView(R.id.id_recyclerview); //設置佈局管理器 mRecyclerView.setLayoutManager(layout); //設置adapter mRecyclerView.setAdapter(adapter) //設置Item增長、移除動畫 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); //添加分割線 mRecyclerView.addItemDecoration(new DividerItemDecoration( getActivity(), DividerItemDecoration.HORIZONTAL_LIST));
ok,相比較於ListView的代碼,ListView可能只須要去設置一個adapter就能正常使用了。而RecyclerView基本須要上面一系列的步驟,那麼爲何會添加這麼多的步驟呢?架構
那麼就必須解釋下RecyclerView的這個名字了,從它類名上看,RecyclerView表明的意義是,我只管Recycler View,也就是說RecyclerView只管回收與複用View,其餘的你能夠本身去設置。能夠看出其高度的解耦,給予你充分的定製自由(因此你才能夠輕鬆的經過這個控件實現ListView,GirdView,瀑布流等效果)。app
1.Activityide
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); } } } }
2.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>
3.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>
這麼看起來用法與ListView的代碼基本一致哈~~
看下效果圖:動畫
看起來好醜,Item間應該有個分割線,當你去找時,你會發現RecyclerView並無支持divider這樣的屬性。那麼怎麼辦,你能夠給Item的佈局去設置margin,固然了這種方式不夠優雅,咱們文章開始說了,咱們能夠自由的去定製它,固然咱們的分割線也是能夠定製的。
咱們能夠經過該方法添加分割線:
mRecyclerView.addItemDecoration()
該方法的參數爲RecyclerView.ItemDecoration,該類爲抽象類,官方目前並無提供默認的實現類(我以爲最好能提供幾個)。
該類的源碼:
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); }
當咱們調用mRecyclerView.addItemDecoration()
方法添加decoration的時候,RecyclerView在繪製的時候,去會繪製decorator,即調用該類的onDraw和onDrawOver方法,
接下來咱們看一個RecyclerView.ItemDecoration
的實現類,該類很好的實現了RecyclerView添加分割線(當使用LayoutManager爲LinearLayoutManager時)。
該類參考自: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); } } }
該實現類能夠看到經過讀取系統主題中的 android.R.attr.listDivider
做爲Item間的分割線,而且支持橫向和縱向。若是你不清楚它是怎麼作到的讀取系統的屬性用於自身,請參考個人另外一篇博文:Android 深刻理解Android中的自定義屬性
獲取到listDivider之後,該屬性的值是個Drawable,在getItemOffsets
中,outRect去設置了繪製的範圍。onDraw中實現了真正的繪製。
咱們在原來的代碼中添加一句:
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
ok,如今再運行,就能夠看到分割線的效果了。
該分割線是系統默認的,你能夠在theme.xml中找到該屬性的使用狀況。那麼,使用系統的listDivider有什麼好處呢?就是方便咱們去隨意的改變,該屬性咱們能夠直接聲明在:
<!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <item name="android:listDivider">@drawable/divider_bg</item> </style>
而後本身寫個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>
如今的樣子是:
固然了,你能夠根據本身的需求,去隨意的繪製,反正是畫出來的,隨便玩~~
ok,看到這,你可能以爲,這玩意真尼瑪麻煩,徹底不能比擬的心愛的ListView。那麼繼續看。
好了,上面實現了相似ListView樣子的Demo,經過使用其默認的LinearLayoutManager。
RecyclerView.LayoutManager吧,這是一個抽象類,好在系統提供了3個實現類:
上面咱們已經初步體驗了下LinearLayoutManager,接下來看GridLayoutManager。
咱們嘗試去實現相似GridView,秒秒鐘的事情:
//mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
只須要修改LayoutManager便可,仍是很nice的。
固然了,改成GridLayoutManager之後,對於分割線,前面的DividerItemDecoration就不適用了,主要是由於它在繪製的時候,好比水平線,針對每一個child的取值爲:
final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight();
由於每一個Item一行,這樣是沒問題的。而GridLayoutManager時,一行有多個childItem,這樣就屢次繪製了,而且GridLayoutManager時,Item若是爲最後一列(則右邊無間隔線)或者爲最後一行(底部無分割線)。
針對上述,咱們編寫了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) { // 列數 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 且縱向滾動 if (orientation == StaggeredGridLayoutManager.VERTICAL) { childCount = childCount - childCount % spanCount; // 若是是最後一行,則不須要繪製底部 if (pos >= childCount) return true; } else // StaggeredGridLayoutManager 且橫向滾動 { // 若是是最後一行,則不須要繪製底部 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
方法中,去判斷若是是最後一行,則不須要繪製底部;若是是最後一列,則不須要繪製右邊,整個判斷也考慮到了StaggeredGridLayoutManager
的橫向和縱向,因此稍稍有些複雜。最重要仍是去理解,如何繪製什麼的不重要。通常若是僅僅是但願有空隙,仍是去設置item的margin方便。
最後的效果是:
ok,看到這,你可能還以爲RecyclerView不夠強大?
可是若是咱們有這麼個需求,縱屏的時候顯示爲ListView,橫屏的時候顯示兩列的GridView,咱們RecyclerView能夠輕鬆搞定,而若是使用ListView去實現仍是須要點功夫的~~~
固然了,這只是皮毛,下面讓你心服口服。
瀑布流式的佈局,其實他能夠實現GridLayoutManager
同樣的功能,僅僅按照下列代碼:
// mRecyclerView.setLayoutManager(new GridLayoutManager(this,4)); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
這兩種寫法顯示的效果是一致的,可是注意StaggeredGridLayoutManager構造的第二個參數傳一個orientation,若是傳入的是StaggeredGridLayoutManager.VERTICAL
表明有多少列;那麼傳入的若是是StaggeredGridLayoutManager.HORIZONTAL
就表明有多少行,好比本例若是改成:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL));
那麼效果爲:
能夠看到,固定爲4行,變成了左右滑動。有一點須要注意,若是是橫向的時候,item的寬度須要注意去設置,畢竟橫向的寬度沒有約束了,應爲控件能夠橫向滾動了。
若是你須要同樣橫向滾動的GridView,那麼恭喜你。
ok,接下來準備看大招,若是讓你去實現個瀑布流,最起碼不是那麼隨意就能夠實現的吧?可是,若是使用RecyclerView,分分鐘的事。
那麼如何實現?其實你什麼都不用作,只要使用StaggeredGridLayoutManager
咱們就已經實現了,只是上面的item佈局咱們使用了固定的高度,下面咱們僅僅在適配器的onBindViewHolder
方法中爲咱們的item設置個隨機的高度(代碼就不貼了,最後會給出源碼下載地址),看看效果圖:
是否是棒棒噠,經過RecyclerView去實現ListView、GridView、瀑布流的效果基本上沒有什麼區別,並且能夠僅僅經過設置不一樣的LayoutManager便可實現。
還有更nice的地方,就在於item增長、刪除的動畫也是可配置的。接下來看一下ItemAnimator。
ItemAnimator也是一個抽象類,好在系統爲咱們提供了一種默認的實現類,期待系統多
添加些默認的實現。
藉助默認的實現,當Item添加和移除的時候,添加動畫效果很簡單:
// 設置item動畫 mRecyclerView.setItemAnimator(new DefaultItemAnimator());
系統爲咱們提供了一個默認的實現,咱們爲咱們的瀑布流添加以上一行代碼,效果爲:
若是是GridLayoutManager呢?動畫效果爲:
注意,這裏更新數據集不是用adapter.notifyDataSetChanged()
而是 notifyItemInserted(position)
與notifyItemRemoved(position)
不然沒有動畫效果。
上述爲adapter中添加了兩個方法:
public void addData(int position) { mDatas.add(position, "Insert One"); notifyItemInserted(position); } public void removeData(int position) { mDatas.remove(position); notifyItemRemoved(position); }
Activity中點擊MenuItem觸發:
@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; }
好了,到這我對這個控件已經不是通常的喜歡了~~~
固然了只提供了一種動畫,那麼咱們確定能夠去自定義各類nice的動畫效果。
高興的是,github上已經有不少相似的項目了,這裏咱們直接引用下:RecyclerViewItemAnimators,你們本身下載查看。
提供了SlideInOutLeftItemAnimator
,SlideInOutRightItemAnimator
, SlideInOutTopItemAnimator
,SlideInOutBottomItemAnimator
等動畫效果。
不過一個挺鬱悶的地方就是,系統沒有提供ClickListener和LongClickListener。
不過咱們也能夠本身去添加,只是會多了些代碼而已。
實現的方式比較多,你能夠經過mRecyclerView.addOnItemTouchListener去監聽而後去判斷手勢,
固然你也能夠經過adapter中本身去提供回調,這裏咱們選擇後者,前者的方式,你們有興趣本身去實現。
那麼代碼也比較簡單:
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)); // 若是設置了回調,則設置點擊事件 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; } }); } } //... }
adapter中本身定義了個接口,而後在onBindViewHolder中去爲holder.itemView去設置相應
的監聽最後回調咱們設置的監聽。
最後別忘了給item添加一個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中去設置監聽:
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常見用法,包含了:
能夠看到RecyclerView能夠實現:
整個體驗下來,感受這種插拔式的設計太棒了,若是系統再能提供一些經常使用的分隔符,多添加些動畫效果就更好了。
經過簡單改變下LayoutManager,就能夠產生不一樣的效果,那麼咱們能夠根據手機屏幕的寬度去動態設置LayoutManager,屏幕寬度通常的,顯示爲ListView;寬度稍大的顯示兩列的GridView或者瀑布流(或者橫縱屏幕切換時變化,有點意思~);顯示的列數和寬度成正比。甚至某些特殊屏幕,讓其橫向滑動~~再選擇一個nice的動畫效果,相信這種插件式的編碼體驗必定會讓你迅速愛上RecyclerView。
Android 自定義RecyclerView 實現真正的Gallery效果
A First Glance at Android’s RecyclerView
https://github.com/gabrielemariotti/RecyclerViewItemAnimators