所以我想通过SharedPreferences在RecyclerView适配器类中保存CheckBox状态,如下所示:
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()){
title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
title.setAlpha(0.5f);
PreferenceManager.getDefaultSharedPreferences(c).edit().putBoolean("checkBox", checkBox.isChecked()).commit();
} else if (!checkBox.isChecked()){
title.setPaintFlags(0);
title.setAlpha(0.8f);
PreferenceManager.getDefaultSharedPreferences(c).edit().putBoolean("checkBox", checkBox.isChecked()).commit();
}
}
});
不要介意油漆标志。
我正在这样的活动中检索数据(在onCreate中):
checkBox = (CheckBox) findViewById(R.id.checkBoxDoneOrNotNaListi);
boolean checked = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("checkBox", false);
checkBox.setChecked(checked);
并获取NullPointerException
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference
我做错了什么?
最佳答案
/**
* save selected <position, checkBoxState>
*/
private SparseBooleanArray mSelectedItem = new new SparseBooleanArray(listData.size());
/**
* true: allow checkbox change, else otherwise
* purpose update checkbox state on bind data
*/
private boolean isAllowOnCheckChange = true;
@onBindViewHolder
isAllowOnCheckChange = false;
itemHolder.checkBox.setChecked(mSelectedItem.get(position));
isAllowOnCheckChange = true;
itemHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isAllowOnCheckChange)
mSelectedItem.put(position, isChecked);
}
});