簡體   English   中英

盡管使用了共享首選項,但如何保存我的 cardView 單擊事件狀態以保存其顏色

[英]How can I save my cardView click event state to save its colour in spite of using shared preferences

我正在我的 android 應用程序上實現共享首選項,我想保存 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,則將顏色更改為您想要的顏色

我查看了我自己的代碼片段,如果這是我的代碼,我的代碼與您的代碼的唯一區別是“Context.MODE_PRIVATE”,所有這些行都是:

SharedPreferences.Editor editor = getActivity ().getSharedPreferences ("save",MODE_PRIVATE).edit ();

所以基本上這沒什么大不了的,但你無論如何都可以嘗試一下,它可能有效,更換

“Context.MODE_PRIVATE”

“MODE_PRIVATE”

當然,您還需要一種在創建視圖時檢索這些值的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM