Alejandro Pacheco Alejandro Pacheco - 4 months ago 8
Java Question

Optimize java assignments

I have some bindings that share the same root, Is there a way to shorten the code with a while loop that iterate across all of them?

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


Can reflection be use to make this code less verbose?
My interest is mostly to make it easier to bind > 40 RadioGroups and TextViews.

Answer

You can try this

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);
 }
Comments