朋友,
我正在使用以下代码检查/取消选中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);
}
当我选中任何复选框并滚动它。选中复选框不再检查。 任何人都指导我在这做什么错误?
答案 0 :(得分:9)
您可以尝试使用静态侦听器(可能无法纠正您的错误,但肯定会降低您正在创建的“临时”对象的数量):
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);
}
});