如何使用Firebase使用CheckBox创建合适的回收者视图,目前我可以创建5个viewHolders,一切正常,当我创建6个或更多viewHolder时,复选框开始随机检查。有人做过类似的事情吗?任何帮助将不胜感激!
当前,这是我的OnBindViewHolder:
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position){
final Habitos habitos = mHabitosList.get(position);
holder.nombre.setText(habitos.getNombre());
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference("Habitos");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
userId = user.getUid();
habitosReference = mDatabaseReference.child(userId);
Focus focus = new Focus();
mDays = focus.getPrevFiveDaysNumbers();
habitosId = mHabitosList.get(position).getHabitosId();
habitosReference.child(habitosId).child("checks").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mChecks = (HashMap<String, Boolean>) dataSnapshot.getValue();
Log.d("Checky", mChecks+"");
assert mChecks != null;
checkBox1 = mChecks.get(mDays[0]);
checkBox2 = mChecks.get(mDays[1]);
checkBox3 = mChecks.get(mDays[2]);
checkBox4 = mChecks.get(mDays[3]);
checkBox5 = mChecks.get(mDays[4]);
checkListeners(holder, habitos);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
要收听复选框,我有以下方法:
private void checkListeners(MyViewHolder holder, final Habitos habitos) {
holder.CB1.setChecked(checkBox1);
holder.CB1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String HabitosId = habitos.getHabitosId();
int total = habitos.getTotal();
if (b) {
habitosReference.child(HabitosId).child("checks").child(mDays[0]).setValue(true);
total++;
} else {
habitosReference.child(HabitosId).child("checks").child(mDays[0]).setValue(false);
total--;
}
habitosReference.child(HabitosId).child("total").setValue(total);
}
});
每次选中复选框时,都会添加+1值。除非我添加了5个以上的viewHolders,否则一切都正常。知道我该如何解决吗?