Android RecyclerView 实现多布局java代码实现
时间: 2023-02-20 08:46:44 浏览: 100
下面是一个使用RecyclerView实现多布局的示例代码:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Object> items;
private final int USER = 0, IMAGE = 1;
public MyAdapter(List<Object> items) {
this.items = items;
}
@Override
public int getItemViewType(int position) {
Object object = items.get(position);
if (object instanceof User) {
return USER;
} else if (object instanceof Image) {
return IMAGE;
}
return -1;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == USER) {
view = layoutInflater.inflate(R.layout.user_layout, parent, false);
return new UserViewHolder(view);
} else if (viewType == IMAGE) {
view = layoutInflater.inflate(R.layout.image_layout, parent, false);
return new ImageViewHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object object = items.get(position);
if (object instanceof User) {
((UserViewHolder) holder).bindView((User) object);
} else if (object instanceof Image) {
((ImageViewHolder) holder).bindView((Image) object);
}
}
@Override
public int getItemCount() {
return items.size();
}
private class UserViewHolder extends RecyclerView.ViewHolder {
private TextView name;
public UserViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
}
public void bindView(User user) {
name.setText(user.getName());
}
}
private class ImageViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
public ImageViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
public void bindView(Image image) {
this.image.setImageDrawable(image.getImage());
}
}
}
阅读全文