1

im doing a application to see if a checkedBox is checked, But i have 21 checkbox, and i need to get the id of all checkbox to make an operation.

Is there a way to get all id to an array without doing it manually? i mean without doing the cast 21 times.~ like this.

CheckBox MineBox = (CheckBox) findViewById(R.id. ""); i dont want to do this. plis help me

Talisson Junior
  • 79
  • 2
  • 11
  • Have a look at Butter Knife: http://jakewharton.github.io/butterknife/ – Ken Wolf Oct 23 '15 at 12:25
  • Possible duplicate of [Android: Using findViewById() with a string / in a loop](http://stackoverflow.com/questions/4865244/android-using-findviewbyid-with-a-string-in-a-loop) – OneCricketeer Oct 23 '15 at 12:47

2 Answers2

0

Maybe you could wrap your Checkboxes in a RecyclerView?
Elsewise.. here is the code, but it's really ugly, and be careful with naming conventions for your Checkboxes in xml. (here: android:id = "@+id/checkBox0"

CheckBox[] checkBoxList = new CheckBox[20];

for (int i = 0; i < 20, i++){
    String checkBoxID = "checkBox" + i;
    int resID = getResources().getIdentifier(checkBoxID, "id", "com.your.projectname");
    checkBoxList[i] = findViewById(resID);

}
yennsarah
  • 5,467
  • 2
  • 27
  • 48
  • CheckBoxList[i] = findViewByid(resID); i got an erro here – Talisson Junior Oct 23 '15 at 13:11
  • Make sure that you are naming your Checkboxes correctly in your xml - especially check the small/capital letters. If you are calling this inside a special view, you'll need to call findViewById on it. Have you changed the package name correctly? – yennsarah Oct 23 '15 at 13:22
  • I think you'll need to cast your View to Checkbox on the last line. – yennsarah Oct 23 '15 at 13:39
0

Use this:

for(int i=0; i<xvalue; i++) {
   for(int j=0; j<yvalue; j++) {
    String checkID = "chk" + i + "-" + j;
    int id = getResources().getIdentifier(checkID, "id", "com.xx.xx");
    checks[i][j] = ((Button) findViewById(id));
    checks[i][j].setOnClickListener(this);
   }
}
josedlujan
  • 5,357
  • 2
  • 27
  • 49