4

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.

mpromonet
  • 10,379
  • 42
  • 54
  • 85
Alejandro
  • 219
  • 2
  • 13

1 Answers1

4

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);
 }
Robin-Hoodie
  • 4,736
  • 4
  • 25
  • 59
Shunan
  • 2,986
  • 6
  • 26
  • 47