首页 > 解决方案 > Android:将 Checkbox 对象转换为应用一组规则的数组

问题描述

我是编码新手,所以我不完全确定我要问的内容是否有意义。如果没有,请告诉我。

我正在 android 中开发一个测验,我在我的 java 文件中创建了四个 Checkbox 对象。对每个 Checkbox 对象都会应用一组规则。要应用的规则都是一样的。这是我的代码:

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

[...]

方法:

    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) {...}

因为我对相同的对象类型使用相同的规则,所以使用数组不会使这个过程更加直接和优雅吗?如果可以,我将如何做到这一点?

非常感谢您的时间和帮助!

标签: javaandroidarraysobjectcheckbox

解决方案


我认为这解决了我的问题:

byte i, numberOfCheckedBoxesQ2 = 0;
final byte NUMBER_OF_CHECKBOXES_FOR_Q2 = 4;
int[] idsQ2A = {R.id.Q2A1, R.id.Q2A2, R.id.Q2A3, R.id.Q2A4};
boolean[] hasCorrectAnswerForQ2A = new boolean[NUMBER_OF_CHECKBOXES_FOR_Q2];
CheckBox[] Q2A = new CheckBox[NUMBER_OF_CHECKBOXES_FOR_Q2];

[...]

方法:

for (i = 0; i < NUMBER_OF_CHECKBOXES_FOR_Q2; i++) {
        Q2A[i] = findViewById(idsQ2A[i]);
        hasCorrectAnswerForQ2A[i] = Q2A[i].isChecked();
        if (hasCorrectAnswerForQ2A[i]) {numberOfCheckedBoxesQ2 += 1;}
    }

我还没有尝试过 lambda,但我稍后会看一下。再次感谢!@大卫易卜拉欣@pafau k。


推荐阅读