我尝试了SharedPreferences,但没有成功。 为什么不保存toogle状态?
我正在使用RegleerView中的一个切换按钮。
这是我的onBindViewHolder()代码:
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
final ToggleModel toggleModel = toggleModelList.get(position);
if(toggleModel.isFavorite())
holder.toggle_btn.setBackgroundResource(toggleModel.getToggled());
else
holder.toggle_btn.setBackgroundResource(toggleModel.getUntoglled());
//Set title from model
holder.textView.setText(toggleModel.getTitle());
((ViewHolder) holder).copybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(view.getContext(), "dfdfd", Toast.LENGTH_SHORT).show();
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(holder.textView.getText().toString());
Toast.makeText(context, "Copied :)", Toast.LENGTH_SHORT).show();
}
});
holder.toggle_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final SharedPreferences preferences = context.getSharedPreferences("save",Context.MODE_PRIVATE);
if (toggleModel.isFavorite) {
toggleModel.setFavorite(false);
Toast.makeText(context, "UNFavorited", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.apply();
}
else {
toggleModel.setFavorite(true);
Toast.makeText(context, "Favorited", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.apply();
//Log.e("IN ELSE PART",editor.apply());
}
notifyItemChanged(position);
}
});
}
任何人都可以请提供您宝贵的建议