我很困惑,在滚动时可以在ListView中保存CheckBox的状态之前,但是现在不保存!我看到了许多解决方案,但我的适配器类没有看到任何错误。请查看它,并通知我应该在哪里更改代码!
public class CustomListAdapter extends BaseAdapter {
protected ArrayList listData;
protected LayoutInflater layoutInflater;
private SharedPreferences sp;
private Editor editor;
public CustomListAdapter(Context context, ArrayList listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
sp=context.getSharedPreferences("sp", Activity.MODE_PRIVATE);
editor=sp.edit();
}
public CustomListAdapter(OnClickListener onClickListener,
ArrayList image_details) {
// TODO Auto-generated constructor stub
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setListData(ArrayList listdata){
this.listData=listdata;
}
public void remove(int i){
listData.remove(i);
}
@SuppressLint("NewApi")
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.cb_mark=(CheckBox) convertView.findViewById(R.id.cb_search_mark);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Aye aye = (Aye)listData.get(position);
aye.setMarked(sp.getBoolean("CheckValue"+position, false));
holder.cb_mark.setChecked(aye.isMarked());
holder.cb_mark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
aye.setMarked(arg1);
editor.putBoolean("CheckValue"+position, arg1);
editor.commit();
Log.i("CheckValue"+position, sp.getBoolean("CheckValue"+position, false)+"");
}
});
holder.cb_mark.setChecked(aye.isMarked());
return convertView;
}
static class ViewHolder {
CheckBox cb_mark;
}
}
最佳答案
可能由于position
上的onCheckedChanged
值错误而出现问题。尝试是通过使用setTag
方法保存当前项目位置,然后在getTag
内部使用onCheckedChanged
来获取位置:
aye.setMarked(sp.getBoolean("CheckValue"+position, false));
holder.cb_mark.setChecked(aye.isMarked());
holder.cb_mark.setTag(position); //<< store position of view
holder.cb_mark.setOnCheckedChangeListener(....{
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
aye.setMarked(arg1);
int pos=Integer.parseInt(arg0.getTag().toString());
editor.putBoolean("CheckValue"+pos, arg1);
editor.commit();
}
});