java - 尽管使用共享首选项,如何保存我的 cardView 点击事件状态以保存其颜色
问题描述
我在我的 android 应用程序上实现共享首选项,我想保存点击监听器事件,即 cardView 颜色已更改并保持这种状态,即使应用程序被杀死或重述但不幸的是我似乎没有在这里得到它,代码运行完美顺利,但cardview状态没有保存谢谢大家,
这是我实施的 cardView 的片段
```//saving button state after one click of the student
SharedPreferences preferences = this.getActivity().getSharedPreferences("save", Context.MODE_PRIVATE);
cardView.setEnabled (preferences.getBoolean ("value",true));
//setting the click listener to send the request to specific section api anf return response
cardView.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
if(cardView.getCardBackgroundColor ().getDefaultColor () ==-1 || textView.getTextColors ().getDefaultColor () ==-1 || cardView.isEnabled ())
{
//change background color
cardView.setCardBackgroundColor (Color.parseColor ("#2b434f"));
textView.setTextColor (Color.parseColor ("#ffffff"));
Toast.makeText (getActivity (),"Request Sent to SNAL",Toast.LENGTH_LONG).show ();
SharedPreferences.Editor editor = getActivity ().getSharedPreferences ("save",Context.MODE_PRIVATE).edit ();
editor.putBoolean ("value",true);
editor.apply ();
//disabling the button after one click
cardView.setEnabled (true);
}
else {
cardView.setCardBackgroundColor (Color.parseColor ("#ffffff"));
textView.setTextColor (Color.parseColor ("#2b434f"));
SharedPreferences.Editor editor = getActivity ().getSharedPreferences ("save",Context.MODE_PRIVATE).edit ();
editor.putBoolean ("value",false);
editor.apply ();
cardView.setEnabled (true);
}
}
});```
解决方案
即使您保存状态,您也需要在 onCreate/onStart/onResume(或单击之前的任何时间)中添加一个功能,如果该值为 true,则将颜色更改为您想要的颜色
推荐阅读
- sql - 如何在 SQL 中计算行中的累积总和
- paw-app - Paw 请求中的数字动态数
- javascript - odoo 表单视图从 js 更新另一个字段的值
- php - Mysql连接超时与utf8mb4升级
- knockout.js - DOTVVM:如何实现 DraggableList(不工作)
- android - Gradle 失败 - null VariantManager
- rabbitmq - RabbitMQ 的默认消费者线程值?
- r - 具有皮尔逊相关性的层次聚类
- c# - 唯一标识 Microsoft Office Excel 文件
- reactjs - 获取 JSON 数据数组,如何将其与 React Bootstrap Table 一起使用?