我有一些共享相同根的绑定,有没有办法用迭代遍历所有这些的while循环来缩短代码?
RadioGroup G1, G2.. ... ...; // At class scope
TextView result1... .. ..;
/** ... */
public void bindViews() {
G1 = (RadioGroup) findViewById(R.id.radioGroup1);
G2 = (RadioGroup) findViewById(R.id.radioGroup2);
G3 = (RadioGroup) findViewById(R.id.radioGroup3);
G4 = (RadioGroup) findViewById(R.id.radioGroup4);
G5 = (RadioGroup) findViewById(R.id.radioGroup5);
G6 = (RadioGroup) findViewById(R.id.radioGroup6);
G7 = (RadioGroup) findViewById(R.id.radioGroup7);
G8 = (RadioGroup) findViewById(R.id.radioGroup8);
G9 = (RadioGroup) findViewById(R.id.radioGroup9);
G10 = (RadioGroup) findViewById(R.id.radioGroup10);
G11 = (RadioGroup) findViewById(R.id.radioGroup11);
G12 = (RadioGroup) findViewById(R.id.radioGroup12);
G13 = (RadioGroup) findViewById(R.id.radioGroup13);
G14 = (RadioGroup) findViewById(R.id.radioGroup14);
G15 = (RadioGroup) findViewById(R.id.radioGroup15);
G16 = (RadioGroup) findViewById(R.id.radioGroup16);
G17 = (RadioGroup) findViewById(R.id.radioGroup17);
G18 = (RadioGroup) findViewById(R.id.radioGroup18);
G19 = (RadioGroup) findViewById(R.id.radioGroup19);
G20 = (RadioGroup) findViewById(R.id.radioGroup20);
....
}
可以使用反射来使这段代码更简洁吗? 我的兴趣主要是为了让绑定>更容易40 RadioGroups 和 TextViews 。
答案 0 :(得分:4)
你可以试试这个
int count = 40;
RadioGroup G[] = new RadioGroup[count];
for(int i = 1 ; i < count ; i++){
String temp = "radioGroup" + i;
int id = getResources().getIdentifier(temp, "id", getPackageName());
G[i] = (RadioGroup) findViewById(id);
}