我的代码有问题,我在一个 recyclerview 中创建了两个适配器。我把它们都放在一个类中,我需要这个适配器根据某些情况返回一个 Viewholder。
这是我的适配器代码:
public class CurrentUserTaskListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<Task> taskList;
private static final int ITEM_TYPE_PUBLISHED_TASK = 1;
private static final int ITEM_TYPE_ASSIGNED_TASK = 2;
public CurrentUserTaskListAdapter(List<Task> taskList) {
this.taskList = taskList;
}
public class AssignedTaskViewHolder extends RecyclerView.ViewHolder {
View mView;
public TextView tvTagAndDate;
public TextView tvStatus;
public AssignedTaskViewHolder(View itemView) {
super(itemView);
mView = itemView;
tvTagAndDate = itemView.findViewById(R.id.tvTagAndDate);
tvStatus = itemView.findViewById(R.id.tvStatus);
}
}
public class PublishedTaskViewHolder extends RecyclerView.ViewHolder {
View mView;
public TextView tvTagAndDate;
public TextView tvStatus;
public PublishedTaskViewHolder(View itemView) {
super(itemView);
mView = itemView;
tvTagAndDate = itemView.findViewById(R.id.tvTagAndDate);
tvStatus = itemView.findViewById(R.id.tvStatus);
}
}
@Override
public int getItemViewType(int position) {
if (taskList.get(position).getAssignedTo() == null)
return ITEM_TYPE_PUBLISHED_TASK;
else
return ITEM_TYPE_ASSIGNED_TASK;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
if(i == ITEM_TYPE_ASSIGNED_TASK){
layoutInflater.inflate(R.layout.layout_curent_user_assigned_tasks_item, viewGroup, false);
return new AssignedTaskViewHolder(viewGroup);
}
else if (i == ITEM_TYPE_PUBLISHED_TASK){
layoutInflater.inflate(R.layout.layout_current_user_pending_tasks, viewGroup, false);
return new PublishedTaskViewHolder(viewGroup);
}
return null;
}
在 getItemViewType 方法中,我验证列表中的对象是哪个类型。
守着星空守着你
相关分类