java - 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) {...}
因为我对相同的对象类型使用相同的规则,所以使用数组不会使这个过程更加直接和优雅吗?如果可以,我将如何做到这一点?
非常感谢您的时间和帮助!
解决方案
我认为这解决了我的问题:
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。
推荐阅读
- mysql - 在 MySQL 存储过程中,如何过滤从字符串列表中的任何一个开始的记录?
- java - 无法将字符串转换为 Int 进行求和
- python - 如何使用for循环计算函数的方差?
- google-chrome - 尽管不是默认浏览器,但如何在 Chrome 中打开超链接?
- c - 一种从 C 内部退出系统 shell (/bin/sh) 的方法
- graphql - Apollo chache.WriteQuery
- javascript - 如何在 Three.js 中将缓冲几何转换为几何
- javascript - Chrome 扩展:通过 popup.js 中的 tab.id 检索缓存数据的语法
- java - 我们如何在不改变大小的情况下保存缓冲图像?
- html - 如何使我的页面不显示为放大?