这可以更轻松吗?Java初学者问题

sor*_*ist 1 java android

我需要创建一系列对象,它现在看起来很丑陋:

CheckBox checkOne = (CheckBox) findViewById(R.id.checkOne);
CheckBox checkTwo = (CheckBox) findViewById(R.id.checkTwo;
CheckBox checkThree = (CheckBox) findViewById(R.id.checkThree);
CheckBox checkFour = (CheckBox) findViewById(R.id.checkFour);
CheckBox checkFive = (CheckBox) findViewById(R.id.checkFive);
Run Code Online (Sandbox Code Playgroud)

在Java方面我处于中间水平,所以我想做的是做一个for循环,然后使用变量变量.唉,Java不支持这个.有没有,更少递归,这样做的方式?

Don*_*oby 5

假设查找键是整数,你可以这样做:

CheckBox[] boxes = new CheckBox[5];
int[] ids = new int[]{R.id.checkOne, R.id.checkTwo, R.id.checkThree, 
                      R.id.checkFour, R.id.checkFive};

for (int i=0; i<5; i++) {
   boxes[i] = (CheckBox) findViewById(ids[i])
}
Run Code Online (Sandbox Code Playgroud)

如果键是其他的,你当然需要改变ids数组的类型.

如果您可以控制这些键在R类中的保存方式,那么最好只将它们作为数组.

使用Lists而不是数组也可能会更好.