我在我的RecyclerView适配器中将切换按钮用作收藏夹
编辑:以下解决方案有效,但是现在当我收藏一个并重新启动应用程序时,所有按钮都被收藏了,对于不喜欢的情况也是如此,请提供解决方案
这是代码:
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
MyModel myModel = myModelList.get(position);
holder.imageView.setImageResource(myModel.getImage());
holder.textView.setText(myModel.getText());
holder.toggle_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean isFavourite = readStae();
if (isFavourite) {
holder.toggle_btn.setBackgroundResource(R.drawable.fav);
isFavourite = false;
saveStae(isFavourite);
} else {
holder.toggle_btn.setBackgroundResource(R.drawable.unfav);
isFavourite = true;
saveStae(isFavourite);
}
}
});
}
@Override
public int getItemCount() {
return myModelList.size();
}
private void saveStae(boolean isFavourite) {
SharedPreferences aSharedPreferenes = context.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
SharedPreferences.Editor aSharedPreferenesEdit = aSharedPreferenes
.edit();
aSharedPreferenesEdit.putBoolean("State", isFavourite);
aSharedPreferenesEdit.commit();
}
private boolean readStae() {
SharedPreferences aSharedPreferenes = context.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
return aSharedPreferenes.getBoolean("State", false);
}
}
重新启动应用程序时,“收藏夹”按钮不存在。
我在做什么错,请解释解决方案,谢谢
答案 0 :(得分:2)
您正在Click Listener内调用readState()
,所以在onBindViewHolder
上,它将不执行该方法。您需要像这样更改代码。
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
MyModel myModel = myModelList.get(position);
holder.imageView.setImageResource(myModel.getImage());
holder.textView.setText(myModel.getText());
boolean isFavourite = readStae();
if (isFavourite) {
holder.toggle_btn.setBackgroundResource(R.drawable.fav);
} else {
holder.toggle_btn.setBackgroundResource(R.drawable.unfav);
} }
,然后在ViewHolder类中应用点击侦听器。