上一篇博客RecyclerView的基本使用讲述了Recycler最基本的使用方法,这篇博客主要围绕如何在一个RecyclerView呈现不同的Item。
要实现在RecyclerView呈现复合Item,主要要在RecyclerView.adapter中的以下三个方法做处理:
getItemViewType()
onCreateViewHolder()
onBindViewHolder()
具体实现
首先,要呈现出不同Item,那么说明Item会有多个XML文件和对应的不同数据源。简便起见,假设我们的项目中有两种不同的Item,一种是单纯的Image,另外一种则是由多个TextView组成。
数据源定义如下:
private ArrayList<Object> getSampleArrayList() {
ArrayList<Object> items = new ArrayList<>();
items.add(new User("Dany Targaryen", "Valyria"));
items.add(new User("Rob Stark", "Winterfell"));
items.add("image");
items.add(new User("Jon Snow", "Castle Black"));
items.add("image");
items.add(new User("Tyrion Lanister", "King's Landing"));
return items;
}
可以看到,有User和单纯的String两种数据。这两种数据对应的布局文件也不同,那么必然导致需要使用不同的ViewHolder:
ViewHolder1.java
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView label1, label2;
public ViewHolder1(View v) {
super(v);
label1 = (TextView) v.findViewById(R.id.text1);
label2 = (TextView) v.findViewById(R.id.text2);
}
public TextView getLabel1() {
return label1;
}
public void setLabel1(TextView label1) {
this.label1 = label1;
}
public TextView getLabel2() {
return label2;
}