RecyclerView是Android 5.0 materials design中的组件之一,相应的还有CardView、Palette等。它主要的特点就是复用。我们知道,Listview中的Adapter中可以实现ViewHolder的复用。RecyclerView提供了一个耦合度更低的方式来复用ViewHolder,并且可以轻松的实现ListView、GridView以及瀑布流的效果。
1.LinearLayoutManager 现行管理器,支持横向、纵向。
2.GridLayoutManager 网格布局管理器
3.StaggeredGridLayoutManager 瀑布就式布局管理器
使用之前还得加上:
dependencies { compile 'com.android.support:recyclerview-v7:23.4.0' }
也可在这搜索在线下载依赖包
代码如下:MainActivity
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import java.util.ArrayList; /** * 再循环视图,内部实现了复用 */ public class MainActivity extends AppCompatActivity { /** * 复用视图的控件 */ private RecyclerView recyclerView; /** * 显示的数据 */ private ArrayList<String> mDatas; /** * RecyclerView的适配器 */ private MyRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1.找到控件 recyclerView = (RecyclerView) findViewById(R.id.recyclerview); //2.创建布局管理器,LinearLayoutManager代表线性的,也就有垂直和水平方向了 LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); //3.给linearLayoutManager设置滑动的方向 linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); //4.为recyclerView设置布局管理器 recyclerView.setLayoutManager(linearLayoutManager); initData();//初始化数据 //3.创建适配器 adapter = new MyRecyclerViewAdapter(this, mDatas); //设置分割线 recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST)); //设置添加,移除item的动画,DefaultItemAnimator为默认的 recyclerView.setItemAnimator(new DefaultItemAnimator()); //4.设置适配器 recyclerView.setAdapter(adapter); //添加点击事件 adapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnRecyclerItemClickListener() { @Override public void onItemClick(View view, int position) { //Toast.makeText(MainActivity.this,"单击了:"+mDatas.get(position),Toast.LENGTH_SHORT).show(); adapter.addItem(position,"添加的内容"); Log.i("tag", "onItemClick: "+position); Log.i("tag", "集合: "+mDatas.toString()); } }); //设置长按事件 adapter.setOnItemLongClickListener(new MyRecyclerViewAdapter.onRecyclerItemLongClickListener() { @Override public void onItemLongClick(View view, int position) { //Toast.makeText(MainActivity.this,"长按了:"+mDatas.get(position),Toast.LENGTH_SHORT).show(); adapter.removeItem(position); Log.i("tag", "onItemLongClick: "+position); Log.i("tag", "集合: "+mDatas.toString()); } }); } //初始化数据 protected void initData(){ mDatas = new ArrayList<String>(); for (int i = 'A'; i < 'z'; i++){ mDatas.add("" + (char) i); } } }
适配器MyRecyclerViewAdapter
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by my on 2016/9/27. */ public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> { private Context context; private List<String> list; private OnRecyclerItemClickListener mOnItemClickListener;//单击事件 private onRecyclerItemLongClickListener mOnItemLongClickListener;//长按事件 public MyRecyclerViewAdapter(Context context, List<String> list) { this.context = context; this.list = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //找到item的布局 View view= LayoutInflater.from(context).inflate(R.layout.recycler_item_layout,parent,false); return new MyViewHolder(view);//将布局设置给holder } @Override public int getItemCount() { return list.size(); } /** * 绑定视图到holder,就如同ListView的getView(),但是这里已经把复用实现了,我们只需要填充数据就行,复用的时候都是调用该方法填充数据 */ @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { //填充数据 holder.textView.setText(list.get(position)+""); //设置单击事件 if(mOnItemClickListener !=null){ holder.textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //这里是为textView设置了单击事件,回调出去 //mOnItemClickListener.onItemClick(v,position);这里需要获取布局中的position,不然乱序 mOnItemClickListener.onItemClick(v,holder.getLayoutPosition()); } }); } //长按事件 if(mOnItemLongClickListener != null){ holder.textView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { //回调出去 mOnItemLongClickListener.onItemLongClick(v,holder.getLayoutPosition()); return true;//不返回true,松手还会去执行单击事件 } }); } } class MyViewHolder extends RecyclerView.ViewHolder{ TextView textView; public MyViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.textView); } } /** * 处理item的点击事件,因为recycler没有提供单击事件,所以只能自己写了 */ interface OnRecyclerItemClickListener { public void onItemClick(View view, int position); } /** * 长按事件 */ interface onRecyclerItemLongClickListener{ public void onItemLongClick(View view, int position); } /** * 暴露给外面的设置单击事件 */ public void setOnItemClickListener(OnRecyclerItemClickListener onItemClickListener){ mOnItemClickListener = onItemClickListener; } /** * 暴露给外面的长按事件 */ public void setOnItemLongClickListener(onRecyclerItemLongClickListener onItemLongClickListener){ mOnItemLongClickListener = onItemLongClickListener; } /** * 向指定位置添加元素 */ public void addItem(int position, String value) { if(position > list.size()) { position = list.size(); } if(position < 0) { position = 0; } /** * 使用notifyItemInserted/notifyItemRemoved会有动画效果 * 而使用notifyDataSetChanged()则没有 */ list.add(position, value);//在集合中添加这条数据 notifyItemInserted(position);//通知插入了数据 } /** * 移除指定位置元素 */ public String removeItem(int position) { if(position > list.size()-1) { return null; } String value = list.remove(position);//所以还需要手动在集合中删除一次 notifyItemRemoved(position);//通知删除了数据,但是没有删除list集合中的数据 return value; } }
注意这里使用了ViewHolder的getLayoutPosition方法,此方法返回的pos值与onBindViewHolder方法传入的position值有可能不同。根据SDK中的解释,在Recyclerview 进行添加、移除item等操作时,position位置可能会变化,而所有的adapter的刷新并不总是及时的,只有这个方法返回的才是当前item经过一些变换后所处的真正位置。
分割线代码如下:DividerItemDecoration
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.view.View; /** * 当使用LayoutManager为LinearLayoutManager时,可以使用的分割线 * 通过读取系统主题中的android.R.attr.listDivider作为Item间的分割线,并且支持横向和纵向 */ 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); RecyclerView v = new 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); } } }
主布局文件:
<?xml version="1.0" encoding="utf-8"?> <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" tools:context="com.workspace.my.recyclerviewtest.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView> </RelativeLayout>
item布局:recycler_item_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:id="@+id/textView" android:textSize="30sp" android:gravity="center" android:background="#ffcccc" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
效果图:
该分割线是系统默认的,你可以在theme.xml中找到该属性的使用情况。那么,使用系统的listDivider有什么好处呢?就是方便我们去随意的改变,该属性我们可以直接声明在styles.xml(系统的风格)中,在原来的基础上修改:
<resources> <!-- Base application theme. 这里为系统的 --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--修改分割线的颜色,divider_bg为用shape画的--> <item name="android:listDivider">@drawable/divider_bg</item> </style> </resources>
divider_bg.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <!--drawable目录下--> <gradient android:centerColor="#ff00ff00" android:endColor="#ff0000ff" android:startColor="#ffff0000" android:type="linear" /> <size android:height="4dp"/> </shape>
这样分割线就为:
做到这里你可能会觉得实现一个listView的效果并没有比listView的方法简单啊,确实是这样的,但是该控件主要是降低了耦合度,不信你接着看.
你只需要修改MainActivity中的第三步修改为:
//3.给linearLayoutManager设置方向,水平 这样就实现了横向的滑动效果了(分割线的方向也修改下) ,再修改下item的布局文件,就更完美了 linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
=========上面我们已经初步体验了下LinearLayoutManager,接下来看GridLayoutManager。======
2.实现GridView网格布局的效果:由于具有低耦合性,所以这里我们都不需要修改适配器,只需要修改Mainactivity中的部分代码,如下:
//1.找到控件 recyclerView = (RecyclerView) findViewById(R.id.recyclerview); //2.声名gridview布局方式 第二个参数代表是3列的网格视图 (垂直滑动的情况下, 如果是水平滑动就代表3行) GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 3); //3.给GridLayoutManager设置滑动的方向 gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL); //4.为recyclerView设置布局管理器 recyclerView.setLayoutManager(gridLayoutManager);
改为GridLayoutManager以后,对于分割线,前面的DividerItemDecoration就不适用了,因为网格布局需要水平间隔和垂直间隔,所以如果需要间隔就修改DividerItemDecoration类为:
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; /** * 网格布局的分割线 */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; private Drawable mDivider; public DividerItemDecoration(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()); } } }
效果图如下:
一般如果仅仅是希望有空隙,还是去设置item的margin方便。如下:(删除掉MainActivity代码中分割线的设置)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:id="@+id/textView" android:textSize="30sp" android:gravity="center" android:layout_margin="3dp" android:background="#ffcccc" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
效果图如下: 可见效果也是一样的,所以图省事,就设置下margin值吧
如果想实现横向滑动,就只需要将垂直滑动改为水平滑动就可以了,如下:
//3.给GridLayoutManager设置滑动的方向 gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
效果如下: 这里我没有修改布局文件,稍微修改下就好看了
修改几行代码就可以显示不一样的样式,是不是很方便,这就是低耦合的强大之处
RecyclerView的拖拽与滑动删除
mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() { /** * 是否处理滑动事件 以及拖拽和滑动的方向 如果是列表类型的RecyclerView的只存在UP和DOWN, * 如果是网格类RecyclerView则还应该多有LEFT和RIGHT * @param recyclerView * @param viewHolder * @return */ @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (recyclerView.getLayoutManager() instanceof GridLayoutManager) { final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; //final int swipeFlags = 0; final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;//代表处理滑动删除,将执行onSwiped()方法 return makeMovementFlags(dragFlags, swipeFlags); } else { final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; //final int swipeFlags = 0;//为0 代表不处理滑动删除 final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;//代表处理滑动删除,将执行onSwiped()方法 return makeMovementFlags(dragFlags, swipeFlags); } } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { //得到当拖拽的viewHolder的Position int fromPosition = viewHolder.getAdapterPosition(); //拿到当前拖拽到的item的viewHolder int toPosition = target.getAdapterPosition(); if (fromPosition < toPosition) { for (int i = fromPosition; i < toPosition; i++) { Collections.swap(mDatas, i, i + 1);//交换位置 } } else { for (int i = fromPosition; i > toPosition; i--) { Collections.swap(mDatas, i, i - 1); } } adapter.notifyItemMoved(fromPosition, toPosition);//刷新 return true; } /** * 当item被左右滑动时调用 * @param viewHolder * @param direction */ @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); mDatas.remove(position); adapter.notifyItemRemoved(position); Log.e("tag","onSwiped"); } /** * 当Item被长按的时候是否可以被拖拽 * 相当于长按后执行了:mItemTouchHelper.startDrag(holder);//开始拖动 * @return 返回true:长按item时,就可以实现拖动效果 * 返回false:长按item事件就失效了,也就不能直接实现拖动效果了 */ @Override public boolean isLongPressDragEnabled() { return true; } /** * 左右滑动时是否可以执行onSwiped()方法 * @return 返回true:代表左右滑动item时,可以删除 */ @Override public boolean isItemViewSwipeEnabled() { //Log.e("tag","滑动了--isItemViewSwipeEnabled"); return true; } /** * 开始拖拽时调用 * @param viewHolder * @param actionState */ @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { viewHolder.itemView.setBackgroundColor(Color.LTGRAY);//为拖拽的item设置背景颜色 } super.onSelectedChanged(viewHolder, actionState); } /** * 拖拽结束时调用 * @param recyclerView * @param viewHolder */ @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setBackgroundColor(0); Log.e("tag","拖拽结束"); } }); //与RecyclerView绑定 mItemTouchHelper.attachToRecyclerView(recyclerView);
效果图:
如果想前面两个不能拖动,那该怎么办呢?
/** * 当Item被长按的时候是否可以被拖拽 * 相当于长按后执行了:mItemTouchHelper.startDrag(holder);//开始拖动 * @return 返回true:长按item时,就可以实现拖动效果 * 返回false:长按item事件就失效了,也就不能直接实现拖动效果了 */ @Override public boolean isLongPressDragEnabled() { return false; } /** * 设置长按事件 屏蔽isLongPressDragEnabled */ adapter.setOnItemLongClickListener(new MyRecyclerViewAdapter.onRecyclerItemLongClickListener() { @Override public void onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) { Toast.makeText(MainActivity.this,"长按了:"+mDatas.get(position),Toast.LENGTH_SHORT).show(); //如果item不是前两个,则执行拖拽 这样就可以控制了 if(position !=0 && position != 1){ mItemTouchHelper.startDrag(holder);//开始拖动 } } });
效果图: