我列出了以下型号:
name
categoryName
现在,我已经建立了一个Recyclerview,它将具有相同categoryName的所有实体分组:
categoryName1
name1
name2
name3
categoryName2
name4
categoryName3
name5
name6
所以我有两种不同的行类型(不同的样式)。该名单已订购。我不需要代码,但是,适用于适配器的算法是什么?我能用一个周期来解决这个问题吗?
我希望避免从代码中向垂直LinearLayout添加视图。
答案 0 :(得分:2)
您的数据应如下所示:
public class CategorizedName {
private Category category;
private Collection<Name> names = null;
public Category getCategory() {
return category;
}
public Collection<Name> getNames() {
return names;
}
// override hashCode and equals ...
}
在您的适配器中,您应该执行以下操作:
private static final int CATEGORY = 1;
private static final int NAME = 2;
private Collection<CategorizedName> data;
@Override
public int getItemViewType(int position) {
if (items.get(position) instanceof Category) {
return CATEGORY;
} else if (items.get(position) instanceof Name) {
return NAME;
}
throw new RuntimeException('error');
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case CATEGORY:
View categoryView = inflater.inflate(R.layout.viewholder_category, viewGroup, false);
viewHolder = new CategoryViewHolder(categoryView);
break;
case NAME:
View nameView = inflater.inflate(R.layout.viewholder_name, viewGroup, false);
viewHolder = new NameViewHolder(nameView);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
CategoryViewHolder categoryViewHolder = (CategoryViewHolder) viewHolder;
bindCategoryViewHolder(categoryViewHolder, position);
break;
case IMAGE:
NameViewHolder nameViewHolder = (NameViewHolder) viewHolder;
bindNameViewHolder(nameViewHolder, position);
break;
}
}
不要忘记创建视图持有者。
编辑1:为适配器添加了数据结构
答案 1 :(得分:0)
您必须覆盖RecyclerView的方法public int getItemViewType(int position)
,并在public void onCreateViewHolder(ViewGroup parent, int viewType)
示例:
enum Type{Name,Category}
@Override
public int getItemViewType(int position) {
if (position == POSITION_CATEGORY_1 || position == POSITION_CATEGORY_2) {
return Type.Category;
} else {
return Type.Name;}
}
}
结束绑定:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == Type.Category.ordinal()){
return new CategoryItemView(...);
}else {
return new CommonItemView(...);
}
}