首页 > 解决方案 > 尽管使用共享首选项,如何保存我的 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);



               }

           }
       });```

标签: javaandroid

解决方案


即使您保存状态,您也需要在 onCreate/onStart/onResume(或单击之前的任何时间)中添加一个功能,如果该值为 true,则将颜色更改为您想要的颜色


推荐阅读