我的代码有问题,我在一个 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@Overridepublic 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 方法中,我验证列表中的对象是哪个类型。
1 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
修复这部分,例如:
if (i == ITEM_TYPE_ASSIGNED_TASK) {
View view = layoutInflater.inflate(R.layout.layout_curent_user_assigned_tasks_item, viewGroup, false);
return new AssignedTaskViewHolder(view);
} else if (i == ITEM_TYPE_PUBLISHED_TASK) {
View view = layoutInflater.inflate(R.layout.layout_current_user_pending_tasks, viewGroup, false);
return new PublishedTaskViewHolder(view);
}
问题是您正在传递 ViewHolder 的项目布局应该位于的父布局。祝你好运!
添加回答
举报
0/150
提交
取消