我使用的是CheckBoxes,在使用TextViews的时候也遇到了类似的问题,下面的方法可以正常工作,但是是多余的。我在使用TextViews时也做了同样的工作,TextViews的数量为10。
private CheckBox []checkBoxes ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_toast);
checkBoxes = new CheckBox[5];
checkBoxes[0] = findViewById(R.id.checkBox1);
checkBoxes[1] = findViewById(R.id.checkBox2);
checkBoxes[2] = findViewById(R.id.checkBox3);
checkBoxes[3] = findViewById(R.id.checkBox4);
checkBoxes[4] = findViewById(R.id.checkBox5);
}
我已经给复选框的id取了一个通用的名字,有没有什么函数可以用呢,我在想是否有类似下面的方法。
for(int i=1;i<=5;i++){
checkBoxes[i-1]=findViewById(R.id.checkBox(somehow use i));}
或者有什么完全不同的方法,我可以采取吗?
解决方案:
你可以在你的资源中声明一个int数组,其中的条目是你的CheckBox ID。
例如:在你的资源中声明一个int数组,其中的条目就是你的CheckBox ID。
<resources>
<integer-array name="check_box_ids">
<item>@id/checkBox1</item>
<item>@id/checkBox2</item>
<item>@id/checkBox3</item>
<item>@id/checkBox4</item>
</integer-array>
然后,在你的 onCreate
你将循环浏览你的本地数组或你在资源中创建的数组(check_box_ids
)–确保它们都有相同的尺寸!
int[] checkBoxIds = getResources().getIntArray(R.array.check_box_ids);
for (int i = 0; i < checkBoxIds.length; i++) {
checkBoxes[i] = findViewById(checkBoxIds[i]);
}