我正在构建一个项目应用程序,您可以在其中添加用户到任务。我所有的用户都有一个回收者视图。当您点击一个用户时,该用户已添加到阵列列表中,一切正常。我遇到的问题是您无法取消选择用户。点击已选择的用户时,应从阵列列表中删除该用户。你怎么做到这一点?
我的适配器:
public class AddPeopleToTaskAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
public ArrayList<String> peopleToAddToTask = new ArrayList<String>();
public List<PeopleInProject> peopleInProjects;
public Context context;
public AddPeopleToTaskAdapter(Context context, List<PeopleInProject> peopleInProjects) {
this.peopleInProjects = peopleInProjects;
this.context = context;
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.add_people_to_task_recyclerview, viewGroup, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final RecyclerViewHolder viewHolder, final int i) {
final PeopleInProject peopleToAdd = peopleInProjects.get(i);
viewHolder.addedIcon.setVisibility(View.INVISIBLE);
viewHolder.nameLbl.setText(peopleToAdd.getUserName());
viewHolder.setItemClickListenerPeopleToAdd(new ItemClickListenerPeopleToAdd() {
@Override
public void onClick(View view, int position) {
Toast.makeText(context, "You added " + peopleToAdd.getEmail(), Toast.LENGTH_SHORT).show();
peopleToAddToTask.add(peopleToAdd.getUserId().toString());
viewHolder.addedIcon.setVisibility(View.VISIBLE);
viewHolder.addIcon.setVisibility(View.INVISIBLE);
if (peopleToAddToTask.contains(peopleToAdd.getUserId().toString())) {
}
}
});
}
@Override
public int getItemCount() {
return peopleInProjects.size();
}
当添加用户(addedIcon)时,我还会显示图像。正确显示。取消选择用户时,该图像应替换为addIcon。
我尝试过,但是没有用。
@Override
public void onBindViewHolder(@NonNull final RecyclerViewHolder viewHolder, final int i) {
final PeopleInProject peopleToAdd = peopleInProjects.get(i);
viewHolder.addedIcon.setVisibility(View.INVISIBLE);
viewHolder.nameLbl.setText(peopleToAdd.getUserName());
viewHolder.setItemClickListenerPeopleToAdd(new ItemClickListenerPeopleToAdd() {
@Override
public void onClick(View view, int position) {
Toast.makeText(context, "You added " + peopleToAdd.getEmail(), Toast.LENGTH_SHORT).show();
peopleToAddToTask.add(peopleToAdd.getUserId().toString());
viewHolder.addedIcon.setVisibility(View.VISIBLE);
viewHolder.addIcon.setVisibility(View.INVISIBLE);
if (peopleToAddToTask.contains(peopleToAdd.getUserId().toString())) {
peopleToAddToTask.remove(i);
viewHolder.addedIcon.setVisibility(View.INVISIBLE);
viewHolder.addIcon.setVisibility(View.VISIBLE);
}
}
});
}
感谢所有帮助。 Tnx!
答案 0 :(得分:0)
我认为您应该首先遍历数组并检查是否包含该用户
for(int i = 0; i < peopleToAddToTask.size(); i++){
if (peopleToAddToTask.contains(peopleToAdd.getUserId().toString())) {
peopleToAddToTask.remove(i);
viewHolder.addedIcon.setVisibility(View.INVISIBLE);
viewHolder.addIcon.setVisibility(View.VISIBLE);
}
}