您将希望在项目数据中而不是在视图持有者中保留项目的状态。视图持有者只是视图的一种便利,假设您回收视图,它会在不同时间显示许多不同的项目。在数据绑定期间,您需要绑定显示项目所需的所有状态,以避免随机数据出现在另一个列表项的视图中。
public class MyListAdapter extends BaseAdapter {
// ....
@Override
View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflate(R.layout.my_list_item_layout, parent, false);
// View holder just prevents having to look up these values
// every time the view is reused.
MyViewHolder holder = new MyViewHolder();
holder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
holder.textview = (TextView) view.findViewById(R.id.text_view);
view.setTag(holder);
}
final MyViewHolder holder = (MyViewHolder) view.getTag();
final MyData data = (MyData) getItem(position);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.savedCheckboxState = isChecked;
// now tell the view to rebind the data
notifyDataSetChanged();
}
});
holder.checkbox.setChecked(data.savedCheckboxState);
holder.textview.setText(String.valueOf(data.savedCheckboxState));
return view;
}
private static class MyViewHolder {
CheckBox checkbox;
TextView textview;
}
}