我非常喜欢在我滚动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;
}
}
答案 0 :(得分:1)
由于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();
}
});
答案 1 :(得分:0)
我有同样的问题, 这里只是简单的解决方案,如果您正确实现了适配器类。
@Override
public int getViewTypeCount() {
if(getCount() < 1)
return 1;
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}