Android 将多个 ViewHolders 与 ItemViewType 一起使用
例子
有时一个RecyclerView会需要使用几种类型的View来显示在UI显示的列表中,每个View都需要不同的布局xml来膨胀。
对于这个问题,您可以在单个Adapter中使用不同的ViewHolders,通过使用RecyclerView-中的特殊方法getItemViewType(intposition)。
下面是使用两个ViewHolder的示例:
用于显示列表条目的ViewHolder
用于显示多个标题视图的ViewHolder
@Override
publicRecyclerView.ViewHolderonCreateViewHolder(ViewGroupparent,intviewType){
ViewitemView=LayoutInflater.from(context).inflate(viewType,parent,false);
returnViewHolder.create(itemView,viewType);
}
@Override
publicvoidonBindViewHolder(RecyclerView.ViewHolderholder,intposition){
finalItemmodel=this.items.get(position);
((ViewHolder)holder).bind(model);
}
@Override
publicintgetItemViewType(intposition){
returninSearchState?R.layout.item_header:R.layout.item_entry;
}
abstractclassViewHolder{
abstractvoidbind(Itemmodel);
publicstaticViewHoldercreate(Viewv,intviewType){
returnviewType==R.layout.item_header?newHeaderViewHolder(v):newEntryViewHolder(v);
}
}
staticclassEntryViewHolderextendsViewHolder{
privateViewv;
publicEntryViewHolder(Viewv){
this.v=v;
}
@Overridepublicvoidbind(Itemmodel){
//将项目数据绑定到条目视图。
}
}
staticclassHeaderViewHolderextendsViewHolder{
privateViewv;
publicHeaderViewHolder(Viewv){
this.v=v;
}
@Overridepublicvoidbind(Itemmodel){
//将项目数据绑定到标题视图。
}
}