所以我想通过RecyclerView适配器类中的SharedPreferences保存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
我做错了什么?
答案 0 :(得分:0)
/**
* 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);
}
});
答案 1 :(得分:-1)
在适配器类的onBindViewHolder()
中,您可以输入以下内容:
boolean checked = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("checkBox", false);
holder.checkBox.setChecked(checked);
然后你的ViewHolder
应该是这样的:
public class ViewHolder extends RecyclerView.ViewHolder{
public CheckBox checkBox;
public ViewHolder(View itemView){
super(itemView);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBoxDoneOrNotNaListi);
}
}
onClickListener()
看起来像这样:
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (position){
case 0:
PreferenceManager.getDefaultSharedPreferences(c).edit().putBoolean("checkBox0", checkBox.isChecked()).commit();
break;
case 1:
PreferenceManager.getDefaultSharedPreferences(c).edit().putBoolean("checkBox1", checkBox.isChecked()).commit();
break;
...
}
}
});