I’m coding a really basic check list app. The user can add tasks and then check them off. But for some reason, when the user check an item – the position in the list changes. Here are a couple of screenshots to show what I mean. The code of my ListAdapter follows:
(The Number at the end of the list item is it’s position. e.g. Do Laundry [False]0 is item at position 0.)



CODE
class TaskListAdapter extends ArrayAdapter<Task> implements OnCheckedChangeListener
{
Activity context;
View recycledView;
ViewAccessor viewAccessor;
CheckBox checkbox;
int position;
public TaskListAdapter(Activity context, int resource, int textViewResourceId, List<Task> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
this.recycledView = convertView;
if(recycledView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
recycledView = inflater.inflate(R.layout.checkview, null);
this.viewAccessor = new ViewAccessor(recycledView);
this.recycledView.setTag(this.viewAccessor);
this.checkbox = (CheckBox) recycledView.findViewById(R.id.cbTaskCompleted);
this.checkbox.setOnCheckedChangeListener(this);
this.checkbox.setTag((Integer) position);
}else
{
viewAccessor = (ViewAccessor) this.recycledView.getTag();
this.checkbox = viewAccessor.getCheckBox();
}
this.checkbox.setText( taskList.get(position).toString()+String.valueOf(position) );
this.checkbox.setChecked( taskList.get(position).isCompleted );
return recycledView;
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Task taskUnderConsideration = taskList.get( (Integer) buttonView.getTag() ) ;
taskUnderConsideration.setCompleted(isChecked);
buttonView.setText(taskUnderConsideration.toString()+buttonView.getTag().toString());
}
}
class ViewAccessor
{
View v;
CheckBox cb = null;
ViewAccessor(View v)
{
this.v = v;
}
CheckBox getCheckBox()
{
if(cb==null)
cb = (CheckBox) v.findViewById(R.id.cbTaskCompleted);
return cb;
}
}
If you want to show simple row (with single
TextViewandCheckBox), I’ll recommend you to useListView‘s method:It’ll automatically show the (built-in)
CheckBoxwith theTextView.