I have a custom ListViewAdapter with ImageView, TextView and CheckBox.
When I select particular checkBox and scroll down, after scrolling back, checkBox gets unchecked.
I tried few answers but nothing seems to work.
Here is my code:
public class ListViewAdapterDrawer extends ArrayAdapter<String> {
ImageView imageViewSensor;
TextView textViewSensor, textViewLogging;
CheckBox checkBoxSensor;
private boolean[] itemChecked;
int count;
public ListViewAdapterDrawer(Context context, String[] sensorArray) {
super(context, R.layout.adapter_listview_drawer, sensorArray);
itemChecked = new boolean[sensorArray.length];
for (int i = 0; i < this.getCount(); i++) {
itemChecked[i] = false;
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.adapter_listview_drawer, parent, false);
}
imageViewSensor = (ImageView) convertView.findViewById(R.id.imageViewSensor);
textViewSensor = (TextView) convertView.findViewById(R.id.textViewSensor);
checkBoxSensor = (CheckBox) convertView.findViewById(R.id.checkBoxSensor);
checkBoxSensor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBoxSensor.isChecked()){
itemChecked[position] = true;
}else {
itemChecked[position] = false;
}
}
});
checkBoxSensor.setChecked(itemChecked[position]);
return convertView;
}
}
If you read this link regarding how ListView gets recycled, i.e. the recycling mechanism, you should be able to understand why your checkboxes get unselected.
This gives a rather detailed explanation about ListView.
Key Points: