要在RecyclerView中實現多類型布局,可以通過以下步驟實現:
下面是一個簡單的示例代碼:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Item> itemList;
public MyAdapter(List<Item> itemList) {
this.itemList = itemList;
}
@Override
public int getItemViewType(int position) {
return itemList.get(position).getType();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case Item.TYPE_ONE:
View viewOne = inflater.inflate(R.layout.item_one, parent, false);
return new ViewHolderOne(viewOne);
case Item.TYPE_TWO:
View viewTwo = inflater.inflate(R.layout.item_two, parent, false);
return new ViewHolderTwo(viewTwo);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Item item = itemList.get(position);
switch (item.getType()) {
case Item.TYPE_ONE:
((ViewHolderOne) holder).bind(item);
break;
case Item.TYPE_TWO:
((ViewHolderTwo) holder).bind(item);
break;
}
}
@Override
public int getItemCount() {
return itemList.size();
}
public static class ViewHolderOne extends RecyclerView.ViewHolder {
public ViewHolderOne(View itemView) {
super(itemView);
}
public void bind(Item item) {
// Bind data to ViewHolderOne
}
}
public static class ViewHolderTwo extends RecyclerView.ViewHolder {
public ViewHolderTwo(View itemView) {
super(itemView);
}
public void bind(Item item) {
// Bind data to ViewHolderTwo
}
}
}
在這個示例中,Item是一個自定義的數據類,包含了一個getType()方法用于返回布局類型。根據不同的類型,返回不同的ViewHolder來展示不同的布局。在ViewHolder中通過bind()方法綁定數據到布局中。
最后,在Activity或Fragment中實例化MyAdapter并設置給RecyclerView即可實現多類型布局。