使用RecyclerView首先需要导入相应的架包:
compile 'com.android.support:recyclerview-v7:24.0.0-alpha2'
主界面:
<android.support.v7.widget.RecyclerView
android:id="@+id/main_rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_dark"
android:orientation="vertical"
android:gravity="center"
tools:context="com.wanglun.recyclerviewtest.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
/>
<TextView
android:id="@+id/item_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
/>
</LinearLayout>
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyAdapter> {
private Context context;
public RecyclerViewAdapter(Context context){
this.context=context;
}
@Override
public MyAdapter onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i("woyaokk","onCreateViewHolder======================");
MyAdapter myAdapter;
myAdapter=new MyAdapter(LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false));
return myAdapter;
}
@Override
public void onBindViewHolder(MyAdapter holder, int position) {
Log.i("woyaokk", "onBindViewHolder======================" + position);
holder.item_tv.setText("第" + position + "行");
}
@Override
public int getItemCount() {
Log.i("woyaokk","getItemCount======================");
return 40;
}
public class MyAdapter extends RecyclerView.ViewHolder {
TextView item_tv;
public MyAdapter(View itemView) {
super(itemView);
Log.i("woyaokk", "MyAdapter======================");
item_tv= (TextView) itemView.findViewById(R.id.item_tv);
}
}
}
Activity:
main_rv= (RecyclerView) findViewById(R.id.main_rv);
main_rv.setLayoutManager(new LinearLayoutManager(this));
main_rv.setAdapter(new RecyclerViewAdapter(this));
以上就是RecyclerView的基本使用方法。
详解:
1、分割线:
RecyclerView中与ListView不同,没有默认的分割线,需要手动添加,可以使用网上一个开源项目:
2、
RecyclerView.LayoutManager,这是一个抽象类,系统提供了3个实现类:
3、ItemAnimator动画
LinearLayoutManager 线性管理器,支持横向、纵向。
GridLayoutManager 网格布局管理器
StaggeredGridLayoutManager 瀑布就式布局管理器
使用方法类型于:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
或者
main_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.HORIZONTAL));
3、ItemAnimator动画
RecyclerView刷新列表提供了notifyDataSetChanged(),还有添加 notifyItemInserted(position) 指定位置添加一个item和删除 notifyItemRemoved(position)
RecyclerView增加或者删除item时,可以有相应的动画,默认的效果使用的还是:
main_rv.setItemAnimator(new DefaultItemAnimator());
也可以使用itemAnimator实现想要的动画
4、RecyclerView中不包含点击事件,需要我们手动添加点击事件的回调或者在item中直接实现点击事件
5、上拉加载下拉刷新https://github.com/kodyan/SwipeRefreshLayout