2

I have a vertical linear layout of about 40 checkboxes and the java part has an array that has the content of these checkboxes. Is there a way to reduce the java code?

public String[] sur= {"A","B", //about 40 elements};

CheckBox cb1 = (CheckBox) findViewById(R.id.s1);
cb1.setText(sur[0]);
CheckBox cb2 = (CheckBox) findViewById(R.id.s2); 
cb2.setText(sur[1]);
CheckBox cb3 = (CheckBox) findViewById(R.id.s3); 
cb3.setText(sur[2]);
// repeated about 40 times
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
yukixzoon
  • 21
  • 1

2 Answers2

1

You could try something like:

    for(int i = 0; i < count; i++) {
        CheckBox cb = new CheckBox(context);
        cb.setText(sur[i]);
        container.addView(cb);
    } 
John O'Reilly
  • 10,000
  • 4
  • 41
  • 63
0

You can get an id of a view programatically using Resources package:

for (int index = 0; index < 50; index++) {
  int id = getResources().getIdentifier("s" + (index + 1), "id", getPackageName());
  CheckBox cb = (CheckBox) findViewById(id);
  cb.setText(sur[index]);
}
marmor
  • 27,641
  • 11
  • 107
  • 150