jeudi 15 juin 2017

Android How to save the state of checkboxes that are 3 different checked states

I am new to Android development, and I am wondering how to save a checkbox state locally for when the user reopens the app, and the checkbox stays either red, yellow, or green. I have my code in a fragment, and every time I open the app, it is the default red that I had set. I have custom checkboxes where I have them circular, and when the user clicks on the checkbox it stays checked, but changes the colors. I have researched a lot, and I have tried SharedPreferences, but it's not working, and I need to know what the logic is for having the user click the checkbox and to see if it is red, yellow, or green. What I have seen is for a checkbox just being checked once, and that it is saves the state if it is checked or not, but I have checkboxes that are being checked multiple times and changing colors every time. Here is my code for the method I use for the checkboxes:

public int checked(CheckBox checkBox, int count){
    if (checkBox.isChecked()){
        count++;
    } else if (!checkBox.isChecked()){
        checkBox.setChecked(true);
        count++;
    }
    if (count == 1){
        checkBox.setButtonDrawable(R.drawable.custom_yellow_checkbox);
    }
    if (count == 2){
        checkBox.setButtonDrawable(R.drawable.custom_green_checkbox);
    }
    if (count > 2){
        count = 0;
        checkBox.setButtonDrawable(R.drawable.custom_red_checkbox);
    }
    return count;
} 

Here is the checkbox method itself when it is checked.

chkStart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            countStart = checked(chkStart, countStart);
        }
    });

So, I am wondering if there is a way to save the checkbox state inside of the checked method or to have other methods to make this happen. If anyone has the knowledge of having the state saved for the checkboxes and to have them stay a certain drawable with it being checked 0, 1 or 2 times, I would really appreciate it. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire