Hi i'm new to android and doing custom listview with checkbox, in that i'm facing random selection of another list item checkbox while scrolling. I have gone through some threads but didn't solve my problem. Pls help me out from this. Here is my custom adapter
CustomAdapter.java
public class CustomAdapter extends BaseAdapter{
private boolean[] checkBoxState;
private final Activity context;
public final ArrayList<SelectedListModel>list;
private SelectedListModel element;
private ArrayList<SelectedListModel> positions = new ArrayList<SelectedListModel>();
public CustomAdapter(Activity applicationContext,
ArrayList<SelectedListModel> contacts) {
// TODO Auto-generated constructor stub
this.context = applicationContext;
this.list = contacts;
this.checkBoxState=new boolean[contacts.size()];
}
static class ViewHolder {
protected TextView name,number;
protected CheckBox checkbox;
}
public int getCount() {
// TODO Auto-generated method stub
System.out.println("list size:"+list.size());
return list.size();
}
public ArrayList<SelectedListModel> getSelectedItemList() {
// TODO Auto-generated method stub
return positions;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row_listview, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.number = (TextView) convertView.findViewById(R.id.textView2);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
viewHolder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
element = (SelectedListModel)viewHolder.checkbox.getTag();
if(buttonView.isChecked()==true){
checkBoxState[position] = buttonView.isChecked();
element.setSelected(checkBoxState[position]);
positions.add(element);
}else{
checkBoxState[position] = buttonView.isChecked();
element.setSelected(checkBoxState[position]);
positions.remove(element);
}
}
});
viewHolder.checkbox.setTag(list.get(position));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
setNameAndNumber(list.get(position),holder,position);
return convertView;
}
private void setNameAndNumber(SelectedListModel selectedListModel,ViewHolder holder, int position)
{
// TODO Auto-generated method stub
holder.name.setText(selectedListModel.getName());
holder.number.setText(selectedListModel.getNumber());
holder.checkbox.setSelected(selectedListModel.isSelected());
}
}