dimanche 4 mars 2018

validating multiple checkboxes in linear layout

i am trying to make an app that lists all the pre defined tasks a person has to do daily. To mark them i'm using checkboxes in vertical linear layout. I'm using for loop to iterate through the layout. I want that if a checkbox is checked, an integer (total) is incremented by 1 and if it is unchecked then the integer remains same. Here is the method:

    CheckBox checkBox151, checkBox152, checkBox153;
LinearLayout sundayLayout;

int total = 0;
int[] boxState = {2,2,2,2,2,2,2};


public int formIsValid(LinearLayout layout) {
    boolean wasChecked = false;

    for (int i = 0; i < layout.getChildCount(); i++) {
        View v = layout.getChildAt(i);

        if (v instanceof CheckBox) {
            if(((CheckBox) v).isChecked() && boxState[i] == 2 && wasChecked == false){
                total++;
                boxState[i] = 0;
                wasChecked = true;

            }else if (boxState[i] == 1 && wasChecked == true){
                total = total - 1;
                boxState[i] = 2;

            }else if(boxState[i] == 0 && wasChecked == false){
                boxState[i] = 2;
            }
        }
    }
    return total;
}

I tried various logics but what i get eventually is either the number getting incremented ok but decremented when i check the box again (i want to decrement when unchecked) OR the app crashes due to bad logic. Instant help needed. Thanks in advance...




Aucun commentaire:

Enregistrer un commentaire