效果图
1.导入依赖包
在build.gradle(Module:app)的dependencies中加入
compile ‘com.android.support:recyclerview-v7:25.1.0’
这里的版本号与上下保持一致
2.在XML文件中使用
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.csdn.csdn.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerView"/>
</RelativeLayout>
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/textView"/>
</LinearLayout>
3.在Java文件中加载
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
//设置竖向布局
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
/*************************
*布局有三种选择:
*LinerlayoutManager(竖向)
*GridLayoutManager(横向)
*StaggeredGirdLayoutManager(瀑布流式)
***********************/
//加载布局
recyclerView.setLayoutManager(linearLayoutManager);
//高度固定,不是瀑布流时可以节省资源
recyclerView.setHasFixedSize(true);
//设置Adapter
adapter = new Adapter(dataset);
recyclerView.setAdapter(adapter);
此外dataset一般还要进行初始化
private void initDataset() {
dataset = new String[10];
for (int i = 0; i < 10; i++) {
dataset[i] = ("item" + i);
}
}
RecyclerView的使用
4.编写Adapter
Adapter需要继承 RecyclerView,并且复写3个方法:
onCreateViewHolder
onBindViewHolder
getItemCount
(1)onCreateViewHolder
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//获取父容器parent,向parent中填充item子容器。即关联item布局
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
(2)onBindViewHolder
//绑定ViewHolder,即加载数据
public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
holder.textView.setText(dataset[position]);
}
(3)getItemCount
//获取item数目
public int getItemCount() {
return mDataset.size();
}
此外一般还有再写构造器方法与ViewHolder方法
构造器方法用于数据的初始化
//初始化数据
public MyAdapter(List<> mDataSet) {
this.mDataset = mDataSet;
}
ViewHolder方法用于组件的初始化
//加载并初始化组件
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, teacher, detail, day, type, credit;
public ViewHolder(View v) {
super (v);
name = (TextView) v.findViewById(R.id.name);
teacher = (TextView) v.findViewById(R.id.teacher);
detail = (TextView) v.findViewById(R.id.detail);
day = (TextView) v.findViewById(R.id.day);
type = (TextView) v.findViewById(R.id.type);
credit = (TextView) v.findViewById(R.id.credit);
}
}
这些就是RecyclerView的基本用法。
参考资料(包括分割线等扩展功能)
http://jinyudong.com/2014/11/13/Introduce-RecyclerView-%E4%B8%80/
http://blog.csdn.net/lmj623565791/article/details/45059587
http://blog.csdn.net/allen315410/article/details/40379159