UMAR-MOBITSOLUTIONS UMAR-MOBITSOLUTIONS - 1 month ago 17
Android Question

ListView Checkbox problem in CustomAdapter

friends,

i am using following code to check/uncheck checkboxs inside listview

public AdapterBank(Context context,List<Bank> list,ListView lst) {
mInflater = LayoutInflater.from(context);
this.context = context;
listview = lst;
banks= list;
}

public View getView(final int position, View convertView, ViewGroup parent) {

ViewHolder holder;

if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_banks, null);
holder = new ViewHolder();
holder.bankName = (TextView) convertView.findViewById(R.id.bankName);
holder.bankIcon = (ImageView) convertView.findViewById(R.id.bankIcon);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);



} else {
holder = (ViewHolder) convertView.getTag();
}

Bank bank = getItem(position);

holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
banks.get(position).setSelected(isChecked);
//Toast.makeText(context, "" + position, Toast.LENGTH_LONG).show();
}
});


if(bank.isSelected())
{
holder.checkBox.setChecked(true);
}else
{
holder.checkBox.setChecked(false);
}


when i check any checkbox and scroll it. that checked checkbox is not more checked.
any one guide me what mistake am i doing here?

Answer

You could try to have a static listener (might not correct your bug but will surely lower the number of "temp" objects you are creating):

public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_banks, null);
        holder = new ViewHolder();
        holder.bankName = (TextView) convertView.findViewById(R.id.bankName);
        holder.bankIcon = (ImageView) convertView.findViewById(R.id.bankIcon);
        holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
        holder.checkBox.setOnCheckedChangeListener(checkListener);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Bank bank = getItem(position);
    holder.checkBox.setTag(bank);
    holder.checkBox.setChecked(bank.isSelected());

    return convertView;
}

private OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {
   @Override
   public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
     Bank b = (Bank) checkboxView.getTag();
     b.setSelected(isChecked);
   }
});
Comments