在Android中,使用多个视图类型的Recycler视图可以通过以下步骤实现:
public class Item {
private String title;
private int type;
public Item(String title, int type) {
this.title = title;
this.type = type;
}
public String getTitle() {
return title;
}
public int getType() {
return type;
}
}
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView titleTextView;
public ViewHolder1(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.titleTextView);
}
public void bind(Item item) {
titleTextView.setText(item.getTitle());
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder {
private TextView titleTextView;
public ViewHolder2(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.titleTextView);
}
public void bind(Item item) {
titleTextView.setText(item.getTitle());
}
}
public class Adapter extends RecyclerView.Adapter {
private List- items;
public Adapter(List
- items) {
this.items = items;
}
@Override
public int getItemViewType(int position) {
return items.get(position).getType();
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == 1) {
View itemView = inflater.inflate(R.layout.item_view_type1, parent, false);
return new ViewHolder1(itemView);
} else if (viewType == 2) {
View itemView = inflater.inflate(R.layout.item_view_type2, parent, false);
return new ViewHolder2(itemView);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Item item = items.get(position);
if (holder instanceof ViewHolder1) {
((ViewHolder1) holder).bind(item);
} else if (holder instanceof ViewHolder2) {
((ViewHolder2) holder).bind(item);
}
}
@Override
public int getItemCount() {
return items.size();
}
}
RecyclerView recyclerView = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
List- items = new ArrayList<>();
items.add(new Item("Item 1", 1));
items.add(new Item("Item 2", 2));
items.add(new Item("Item 3", 1));
items.add(new Item("Item 4", 2));
Adapter adapter = new Adapter(items);
recyclerView.setAdapter(adapter);
通过上述步骤,您就可以在Android中使用多个视图类型的Recycler视图了。