RecycleView的多布局
Posted 都嘛德红
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RecycleView的多布局相关的知识,希望对你有一定的参考价值。
---恢复内容开始---
1.首先在适配器定义一个枚举:
public enum ITEM_TYPE {
ITEM1,
ITEM2
}
2.然后在 OnCreatedViewHoler中这样写
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ITEM_TYPE.ITEM1.ordinal()) {
return new Item1ViewHolder(mLayoutInflater.inflate(R.layout.item1, parent, false));
} else {
return new Item2ViewHolder(mLayoutInflater.inflate(R.layout.item2, parent, false));
}
}
3。在OnBind方法中 这样写:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof Item1ViewHolder) {
Glide.with(context).load(list.get(position).getThumbnail_pic_s()).into(((Item1ViewHolder) holder).image);
((Item1ViewHolder) holder).text.setText(list.get(position).getTitle());
} else if (holder instanceof Item2ViewHolder) {
Glide.with(context).load(list.get(position).getThumbnail_pic_s()).into(((Item2ViewHolder) holder).image1);
Glide.with(context).load(list.get(position).getThumbnail_pic_s02()).into(((Item2ViewHolder) holder).image2);
Glide.with(context).load(list.get(position).getThumbnail_pic_s03()).into(((Item2ViewHolder) holder).image3);
((Item2ViewHolder) holder).name.setText(list.get(position).getTitle());
}
}
4.在getItemCout中这样写
@Override
public int getItemCount() {
return list == null ? 0 :list.size();
}
5.在getitemType中这样写
return position % 2 == 0 ? ITEM_TYPE.ITEM1.ordinal() : ITEM_TYPE.ITEM2.ordinal();
6.然后下面这样写
//item2的viewholder
public static class Item2ViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final ImageView image1;
private final ImageView image2;
private final ImageView image3;
public Item2ViewHolder(View itemView) {
super(itemView);
name= (TextView) itemView.findViewById(R.id.name);
image1 = (ImageView) itemView.findViewById(R.id.caritem_image1);
image2 = (ImageView) itemView.findViewById(R.id.caritem_image2);
image3 = (ImageView) itemView.findViewById(R.id.caritem_image3);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listeners.onclick(getAdapterPosition());
}
});
}
}
//item1 的ViewHolder
public static class Item1ViewHolder extends RecyclerView.ViewHolder {
TextView text;
private final ImageView image;
public Item1ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
image = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listeners.onclick(getAdapterPosition());
}
});
}
}
//接口回调 ,用于监听条目
interface Listener{
void onclick(int position);
}
---恢复内容结束---
以上是关于RecycleView的多布局的主要内容,如果未能解决你的问题,请参考以下文章
setOnClickListener RecycleView(在一个片段中)导航到另一个片段
E/RecyclerView:没有附加适配器;在片段内的recyclerview上跳过布局