我決定使用RecyclerView來顯示我的數據列表。每個項目/行中都有一個複選框,2個TextViews和一個ImageView。我創建了適配器來處理所有事情,並將檢查的項目添加到我的最終列表中。RecyclerView檢查錯誤的項目,當我向下滾動
問題是,當我檢查一些項目並向下滾動時,某些項目會顯示爲已選中狀態,並且當我向上滾動時,我以前檢查過的項目顯示爲未選中狀態。圖像和文字瀏覽是可以的,但是當向下滾動時,複選框會出現混亂。
這是我的適配器:
public class TeamAdapter extends RecyclerView.Adapter<TeamAdapter.MyViewHolder> {
private Context mContext;
private List<UserProject> UserList;
private UserProject user;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView name, description;
public CircleImageView profile_image;
public CheckBox check;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
description = (TextView) view.findViewById(R.id.description);
profile_image = (CircleImageView) view.findViewById(R.id.profile_image);
check = (CheckBox) view.findViewById(R.id.check);
}
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClickListener(v, getAdapterPosition());
}
}
}
public TeamAdapter(Context mContext, List<UserProject> userList) {
this.mContext = mContext;
this.UserList = userList;
}
@Override
public TeamAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_teams, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final TeamAdapter.MyViewHolder holder, final int position) {
user = UserList.get(position);
holder.name.setText(user.getName());
holder.description.setText(user.getCompany());
if(user.getImageURL() != null && !user.getImageURL().isEmpty()) {
Picasso.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
ActivityTeams.newList.add(UserList.get(position));
}else {
ActivityTeams.newList.remove(UserList.get(position));
}
}
});
}
@Override
public int getItemCount() {
return UserList.size();
}
private TeamAdapter.onRecyclerViewItemClickListener mItemClickListener;
public void setOnItemClickListener(TeamAdapter.onRecyclerViewItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onRecyclerViewItemClickListener {
void onItemClickListener(View view, int position);
}
}
[RecyclerView中的CheckBox繼續檢查不同的項目]的可能重複(https://stackoverflow.com/questions/32427889/checkbox-in-recyclerview-keeps-on-checking-different-items) – TofferJ
它沒有爲我使用這個問題的解決方案。 –