I have created a listview with textview and checkbox. However after scrolling the list down(or up) all the checked items in the list get unselected. How to make the checked checkboxes retain their state after scrolling?
Asked
Active
Viewed 2,505 times
2
-
can you share some code here, so we can be of any help. – faizanjehangir Aug 13 '12 at 08:51
-
Can you provide your code ?? It will be more easy to answer then. – grv_9098 Aug 13 '12 at 08:52
-
I think this has to do with recycling of the views, the same view is used to populate each and every item on the listview. – nandeesh Aug 13 '12 at 08:53
-
Use this link . It helped me. http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php – grv_9098 Aug 13 '12 at 08:54
3 Answers
3
ListView recycles the views every time it is scrolled. That's why the Check-boxes does not retain their states.
To accomplish your task:
- Store the checked items in an array.
- When you click any checkbox in the listview, change the value of that particular item in the array.
- Inside your getView method, check or uncheck the Check-boxes by reading the values from the array.
That way your checkboxes will retain their states. I hope this is clear.

Amit Jayant
- 2,501
- 2
- 29
- 38
0
You need to save the state of your list when you make any changes in the list. You have to maintain an arrayList of your checkedItems. This Post might prove to be more helpful in this regard..

Community
- 1
- 1

faizanjehangir
- 2,771
- 6
- 45
- 83
0
You can use this adapter class and get selected checkbox id by using listview.getPositionForView(cBox)
public class aAdapter extends SimpleAdapter {
//private List<Table> tables;
SharedPreferences prefs;
private Activity activity;
String val = "";
//@SuppressWarnings("unchecked")
public aAdapter(Activity context, List<? extends Map<String, String>> tables, int resource, String[] from,
int[] to) {
super(context, tables, resource, from, to);
//this.tables = (List<Table>) tables;
activity = context;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.reports_list, null);
}
final CheckBox cBox=(CheckBox)row.findViewById(R.id.cb1);
if(bulkflag)
{
cBox.setVisibility(View.VISIBLE);
}
else
{
cBox.setVisibility(View.GONE);
}
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked())
{
//selectedIds.add(recIdArr.get(reportslistview.getPositionForView(cBox)));
System.out.println("position "+reportslistview.getPositionForView(cBox)+" Checked");
}
else
{
System.out.println("position "+reportslistview.getPositionForView(cBox)+" UnChecked");
}
}
});
return row;
}
}

Ram kiran Pachigolla
- 20,897
- 15
- 57
- 78