最近碰到一个需求,需要RecyclerView的list里加载不同形式的item;于是便需要adapter加载不同形式的ViewHolder。
Adapter类
//定义一个Object型的List
List<Object> beans;
//初始化构造器
public ExampleAdapter(Context context, List<Object> beans) {
this.context = context;
this.beans = beans;
}
//根据viewType 加载不同的ViewHolder
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new ViewHolder1(LayoutInflater.from(context).inflate(R.layout.adapter_1, parent, false));
} else if (viewType == 1) {
return new ViewHolder2(LayoutInflater.from(context).inflate(R.layout.adapter_2, parent, false));
}
return null;
}
//定义ViewHolder1 ViewHolder2
public class ViewHolder1 extends RecyclerView.ViewHolder {
@BindView(R.id.text_example1)
TextView text_example1;
public HouseTypeViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder {
@BindView(R.id.text_example2)
TextView text_example2;
public HouseTypeViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
//根据传入的item,判断加载哪个viewHolder,若匹配到的Object是model1类型 则返回的viewType为0,若匹配到的是model2,则返回1,onBindViewHolder会根据此处的返回值加载不同的ViewHolder
@Override
public int getItemViewType(int position) {
if (beans.get(position) instanceof Model1) {
return 0;
} else if (beans.get(position) instanceof Model2) {
return 1;
}
return super.getItemViewType(position);
}
//构造具体view
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
((ViewHolder1) holder).view_example1.setText("example1");
} else {
((ViewHolder2) holder).view_example2.setText("example2");
}
}
Activity类
protected ExampleAdapter exampleAdapter;
private List<Object> model;
//初始化
model = new ArrayList<>();
exampleAdapter= new ExampleAdapter(Activity.this, model);
rv_recyclerview.setAdapter(exampleAdapter);
//实现处根据需求,list add不同model
if (page == 1) {
model.add(Model1实例);
model.addAll(Model2实例);
} else {
model.addAll(Model2实例);
}
exampleAdapter.notifyDataSetChanged();
``` java