I know this question has a lot of answers in the forum, but I tried all answers and none of them works with my code. The checkbox is unchecked whenever the list is scrolled down. Here is my code:
public class ContactsAdapter extends ArrayAdapter<User> {
private LayoutInflater inflater;
boolean[] checkBoxState;
ViewHolder holder;
public ContactsAdapter(Context context, ArrayList<User> list) {
super(context, R.layout.listitemlayout, R.id.itemTextView, list);
inflater = LayoutInflater.from(context);
checkBoxState = new boolean [list.size()];
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listitemlayout, null);
holder.itemTextView = (TextView)convertView.findViewById(R.id.itemTextView);
holder.checkbox = (CheckBox)convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
User user = getItem(position);
holder.itemTextView.setText(user.getName());
holder.checkbox.setTag(user);
holder.checkbox.setChecked(checkBoxState[position]);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(((CheckBox)v).isChecked())
checkBoxState[position]=true;
else
checkBoxState[position]=false;
}
});
return convertView;
}
private class ViewHolder {
TextView itemTextView;
CheckBox checkbox;
}
}
Please anyone can help me?
Have you tired using an OnCheckedChangeListener instead of an OnClickListener
? You can then just assign whatever value you get from isChecked
into your checkBoxState
array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.