class SearchViewHolder extends RecyclerView.ViewHolder{
TextView studentName, studentMatrik, studentPhone, studentAddress, studentStatus, studentMail, studentCon, studentId;
CheckBox checkBox;
Button buttonMap;
DatabaseReference databaseReference;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
boolean isChecked = sharedPreferences.getBoolean("checked", false);
public SearchViewHolder(View itemView) {
super(itemView);
studentName = (TextView) itemView.findViewById(R.id.studentName);
studentMatrik = (TextView) itemView.findViewById(R.id.studentMatrik);
studentPhone = (TextView) itemView.findViewById(R.id.studentPhone);
studentAddress = (TextView) itemView.findViewById(R.id.studentAddress);
studentStatus = (TextView) itemView.findViewById(R.id.studentStatus);
studentMail = (TextView) itemView.findViewById(R.id.studentMail);
studentCon = (TextView) itemView.findViewById(R.id.studentCon);
studentId = (TextView) itemView.findViewById(R.id.studentId);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
buttonMap = (Button) itemView.findViewById(R.id.buttonMap);
buttonMap.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(context, MapsViewActivity.class);
intent.putExtra("Latitude",studentMail.getText().toString());
intent.putExtra("Longitude",studentCon.getText().toString());
intent.putExtra("Address",studentAddress.getText().toString());
context.startActivity(intent);
}
});
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
editor.putBoolean("checked", isChecked);
editor.commit();
String id = studentId.getText().toString();
databaseReference = FirebaseDatabase.getInstance().getReference("student");
String name = "Check";
databaseReference.child(id).child("stat").setValue(name);
notifyDataSetChanged();
} else {
String id = studentId.getText().toString();
databaseReference = FirebaseDatabase.getInstance().getReference("student");
String name = "Not Check";
databaseReference.child(id).child("stat").setValue(name);
notifyDataSetChanged();
}
}
});
}
如何使用共享首选项将适配器中的复选框值保存?虽然我已经尝试了但仍然是错误的...如果我选中了复选框,我希望在我退出并打开应用程序时仍然会选中该复选框,并且当取消选中该复选框时它也将执行相同操作。
答案 0 :(得分:0)
设置
checkBox.setChecked(isChecked);
不能让它按你想要的那样工作吗?
答案 1 :(得分:0)
On Check事件将布尔数据保存到SharedPreferences
,并将列表项的 id作为键。然后将一些代码添加到ViewHolder
以检查SharedPreference
是否应在显示项目之前检查该项目。这样,ViewHolder
可以检查CheckBox
每次显示SharedPreference
时是否检查了值