有了ListView、GridView为什么还需要RecyclerView这样的控件呢?整体上看RecyclerView架构,提供了一种插拔式的体验,高度的解耦,异常的灵活,更高的效率,通过设置它提供的不同LayoutManager,ItemDecoration , ItemAnimator实现更加丰富多样效果。
但是RecyclerView也有缺点和让人头疼的地方:设置列表的分割线时需要自定义,另外列表的点击事件需要自己去实现。
1.导入v7包
要想使用RecyclerView,我们首先要导入support-v7包,因为我用的是android studio所以我们需要在build.gradle加入如下代码用来自动导入support-v7包,记得配置完后重新Build一下工程
dependencies {compile fileTree(include: '*.jar', dir: 'libs')compile 'com.android.support:appcompat-v7:22.2.0'compile 'com.android.support:design:22.2.0'compile 'com.android.support:recyclerview-v7:22.1.0'
}
- 使用RecyclerView
和ListView的写法大概一样:
RecyclerView mRecyclerView= (RecyclerView) this.findViewById(R.id.id_recyclerview);//设置布局管理器mRecyclerView.setLayoutManager(new LinearLayoutManager(this));// 设置item增加和删除时的动画mRecyclerView.setItemAnimator(new DefaultItemAnimator());mHomeAdaper=new HomeAdapter(this, mList);mRecyclerView.setAdapter(mHomeAdaper);
要比listview的设置要复杂一些,主要是需要自己去自定义分割线,设置动画和布局管理器等等。
布局文件activity_recycler_view.xml:
<?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" ><android.support.v7.widget.RecyclerView android:id="@+id/id_recyclerview"android:divider="#FFB900"android:dividerHeight="1dp"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout>
让我们来看看变化最大的Adaper:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
private List<String> mList;private Context mContext;;public HomeAdapter(Context mContext,List<String>mList){this.mContext=mContext;this.mList=mList;}public void removeData(int position) {mList.remove(position);notifyItemRemoved(position);}@Overridepublic MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_recycler, parent,false));return holder;}@Overridepublic void onBindViewHolder(final MyViewHolder holder, final int position){holder.tv.setText(mList.get(position));}@Overridepublic int getItemCount(){return mList.size();}class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv;public MyViewHolder(View view){super(view);tv = (TextView) view.findViewById(R.id.tv_item);}}
}
最大的改进就是对ViewHolder进行了封装定义,不用自己去自定义了,另外Adaper继承RecyclerView.Adapter,在onCreateViewHolder加载条目布局,在onBindViewHolder中将视图与数据进行绑定。
布局文件item_recycler.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:background="@android:color/white"android:layout_height="wrap_content"><TextView android:id="@+id/tv_item"android:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:text="moon" />
</FrameLayout>
来看看效果:
没有分割线,难看的很,下面我们来讲一讲分割线。
- 设置分割线 ItemDecoration
用mRecyclerView.addItemDecoration()来加入分割线,谷歌没有提供默认的分割线需要我们继承RecyclerView.ItemDecoration来自定义分割线:
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;}@Overridepublic void onDraw(Canvas c, RecyclerView parent) {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);}}@Overridepublic 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);}}
}
实现了自定义的分割线,我们只要在setAdapter之前加入如下代码便可加入分割线:
mRecyclerView.addItemDecoration(new DividerItemDecoration(RecyclerViewActivity.this, DividerItemDecoration.VERTICAL_LIST));
自定义点击事件
列表中条目的点击事件需要我们自己来定义,这是一个不尽如人意的地方,但是自定义点击事件的话也并不是很难,在adaper中定义接口并提供回调:
public interface OnItemClickListener{void onItemClick(View view, int position);void onItemLongClick(View view,int position);}public void setOnItemClickListener(OnItemClickListener mOnItemClickListener)
{this.mOnItemClickListener = mOnItemClickListener;
}
接下来对item中的控件进行点击事件监听并回调给我们自定义的监听:
@Overridepublic void onBindViewHolder(final MyViewHolder holder, final int position){holder.tv.setText(mList.get(position));if (mOnItemClickListener != null){holder.tv.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){int pos = holder.getLayoutPosition();mOnItemClickListener.onItemClick(holder.tv,pos);}});holder.tv.setOnLongClickListener(new View.OnLongClickListener() {@Overridepublic boolean onLongClick(View view) {int pos = holder.getLayoutPosition();mOnItemClickListener.onItemLongClick(holder.tv,pos);return false;}});}}
在Activity进行监听:
mHomeAdaper.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {@Overridepublic void onItemClick(View view, int position) {Toast.makeText(RecyclerViewActivity.this,"点击第"+(position+1)+"条",Toast.LENGTH_SHORT).show();}@Overridepublic void onItemLongClick(View view, final int position) {new AlertDialog.Builder(RecyclerViewActivity.this).setTitle("确认删除嘛").setNegativeButton("取消",null).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {mHomeAdaper.removeData(position);}}).show();}});
长按时会弹出对话框,删除时会有消失的动画:
- 实现GridView
只需要自定义横向的分割线然后在代码中设置:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
具体的代码会在下面给的源码中可以看见,实现效果:
实现瀑布流
虽然第三方实现的瀑布流已经很不错了,但是谷歌这次提供的RecyclerView支持瀑布流我们没有理由不去用,因为更稳定,效率更高,自定义能力更强。
我们可以不用写
mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
来设置分割线,可以在item布局文件中定义分割距离 android:layout_margin=”2dp”:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:background="@android:color/white"android:layout_height="wrap_content"android:layout_margin="2dp"><TextView android:id="@+id/tv_item"android:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:text="moon" />
</FrameLayout>
实现瀑布流很简单只要在adaper写一个随机的高度来控制每个item的高度就可以了,通常这个高度是由服务端返回的数据高度来控制的,在这里我们写一个随机的高度来控制每个item的高度:
mHeights = new ArrayList<Integer>();for (int i = 0; i < mDatas.size(); i++){mHeights.add( (int) (100 + Math.random() * 300));}
接着我们在adaper的onBindViewHolder来设置每个item的高度:
LayoutParams lp = holder.tv.getLayoutParams();lp.height = mHeights.get(position);holder.tv.setLayoutParams(lp);
具体的代码请看下面给的demo,来看看效果:
源码说明
在RecyclerViewActivity的initView来配置你想要的效果:
private void initView() {mRecyclerView= (RecyclerView) this.findViewById(R.id.id_recyclerview);//设置GridView
// setGridView();//设置ListView
// setListView();//设置瀑布流setWaterfallView();}
源码下载 :http://download.csdn.net/detail/qq_34476727/9620408