vendredi 22 mai 2020

Android: Transform Checkbox objects into an Array to which apply a set of rules

I am new to coding, so I am not entirely sure what I am about to ask will make sense. Please let me know if it doesn't.

I am developing a quiz in android, and I have created four Checkbox objects in my java file. To each Checkbox object will apply a set of rules. The rules to be applied are all the same. Here is my code:

byte numberOfCheckedBoxesQ2 = 0;
boolean hasCorrectAnswerForQ2A1, hasCorrectAnswerForQ2A2, hasCorrectAnswerForQ2A3, hasCorrectAnswerForQ2A4;
CheckBox Q2A1, Q2A2, Q2A3, Q2A4;

[...]

method:

    Q2A1 = findViewById(R.id.Q2A1);
    hasCorrectAnswerForQ2A1 = Q2A1.isChecked();
    if (hasCorrectAnswerForQ2A1) {numberOfCheckedBoxesQ2 +=1;}

    Q2A2 = findViewById(R.id.Q2A2);
    hasCorrectAnswerForQ2A2 = Q2A2.isChecked();
    if (hasCorrectAnswerForQ2A2) {numberOfCheckedBoxesQ2 +=1;}

    Q2A3 = findViewById(R.id.Q2A3);
    hasCorrectAnswerForQ2A3 = Q2A3.isChecked();
    if (hasCorrectAnswerForQ2A3) {numberOfCheckedBoxesQ2 +=1;}

    Q2A4 = findViewById(R.id.Q2A4);
    hasCorrectAnswerForQ2A4 = Q2A4.isChecked();
    if (hasCorrectAnswerForQ2A4) {numberOfCheckedBoxesQ2 +=1;}

    if (numberOfCheckedBoxesQ2 > 2) {...}

Because I am using the same rules with the same object types, would employing an array not make this process much more straightforward and elegant? And if it would, how exactly would I do that?

Thanks a lot for your time and help!




Aucun commentaire:

Enregistrer un commentaire