我问了一个有关如何使用文本文件保存复选框状态的问题,但建议使用共享首选项。在使用文本文件之前,我曾尝试过此方法,但存在相同的问题-列表中的复选框似乎随机地选中和取消选中。
我的应用程序显示设备上当前安装的应用程序的列表,并显示应用程序的标题,图标和复选框。如果我检查其中一项,然后向下滚动并再次向上备份,则通常会取消选中该项目,并且会随机检查其他项目。我正在尝试获取它,以便从共享的首选项中加载复选框状态,并保存到用户手动选中该复选框时。
这是listview自定义适配器的代码:
public class AppDetailsAdapter extends BaseAdapter {
private List<AppDetails> data;
private Context context;
public AppDetailsAdapter(Context context, List<AppDetails> data) {
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
SharedPreferences settings = context.getSharedPreferences("data",Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.name, false);
checkBox.setChecked(Checked);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle your conditions here
if(checkBox.isChecked()==true){
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.name,true).commit();
Toast.makeText(context,"You selected "+item.name, Toast.LENGTH_SHORT).show();
}
else {
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.name,false).commit();
Toast.makeText(context,"You deselected "+item.name, Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
最佳答案
这是由于视图回收而发生的。
你能尝试一件事:
代替这个
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
写吧
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
再次运行。