在我簡單的adapater中,我想管理項目上的複選框。當我點擊複選框我改變狀態,當我在滾動的複選框狀態是假的,我不能修復我的代碼來解決此問題Android更改適配器上的複選框不能正常工作
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.CustomContactsViewHolder> {
private OnCardClickListener onCardClickListener;
private List<UserPhoneContacts> list = Collections.emptyList();
private Context context;
private Realm realm;
public static OnSelectedContacts onSelectedContacts;
private Map<String, Boolean> checkBoxStates = new HashMap<>();
public ContactsAdapter(List<UserPhoneContacts> list, Context context) {
this.list = list;
this.context = context;
this.realm = Realm.getDefaultInstance();
}
@Override
public CustomContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_item, parent, false);
CustomContactsViewHolder holder = new CustomContactsViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(final CustomContactsViewHolder holder, final int position) {
holder.contact_name.setText(list.get(position).getDisplayName());
holder.contact_mobile.setText(list.get(position).getMobileNumber());
Boolean checkedState = checkBoxStates.get(list.get(position).getMobileNumber());
holder.select_contact.setChecked(checkedState == null ? false : checkedState);
holder.select_contact.setTag(position);
holder.select_contact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onChange((Integer) v.getTag());
}
});
}
private void onChange(int position) {
final UserPhoneContacts item = list.get(position);
if (item == null) {
return;
}
boolean checkedState = checkBoxStates.get(list.get(position).getMobileNumber()) != null;
checkBoxStates.put(item.getMobileNumber(), !checkedState);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return list.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void setData(List<UserPhoneContacts> list) {
this.list = list;
}
public static class CustomContactsViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.contact_name)
TextView contact_name;
@BindView(R.id.contact_mobile)
TextView contact_mobile;
@BindView(R.id.contact_photo)
CircleImageView contact_photo;
@BindView(R.id.select_contact)
CheckBox select_contact;
CustomContactsViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
當我點擊複選框會發生什麼?
點進>檢查,點進>選中,點進>選中,點進>選中,點進>選中
未選中的複選框後,我無法改變複選框的狀態之後,點擊那個
在'的onChange()'方法添加'notifyDatasetChanged()''後checkBoxStates.put(item.getMobileNumber(),檢查);'此行 –
@Anil我得到這個錯誤:'java.lang.IllegalStateException:無法調用此方法,而RecyclerView正在計算佈局或滾動' –
滾動每當setOnCheckedChangeListener被調用,嘗試檢查readyandroid答案。 –