0

If I have too many checkboxes ( more than 50 ) , is there a way i could use the mapping of the checkboxes , inside for loop ? and how will i assign the int inside the findViewById(int).

Something like this : - (array of checkboxes)

for(int i=0 ; i<=99; i++)
checks[i] = (CheckBox)findViewById(what-about-this-int-id);
devcodes
  • 1,038
  • 19
  • 38
  • All on their own individual id? If you had a separate way to choose the correct resource, perhaps a separate array or mapped value... – FelixMarcus May 14 '15 at 02:49

4 Answers4

2

You can look up resource id's dynamically too using getResources().getIdentifier(..): https://stackoverflow.com/a/14058142/1715829

Community
  • 1
  • 1
Buddy
  • 10,874
  • 5
  • 41
  • 58
0

If you have a container element where all those checkboxes reside then you can simply get all its checkbox children by casting it to ViewGroup

ViewGroup container = (ViewGroup)findViewById(R.id.container);
for (int i = 0; i < container.getChildCount(); i++){
   CheckBox cb = (CheckBox)container.getChildAt(i);
   // attach  listener etc    
}
inmyth
  • 8,880
  • 4
  • 47
  • 52
0

I know you might have found your solution but just in case others couldn't find a proper one, i'll post mine here.

Let's say you labelled your "findViewById" like this:

<CheckBox
    android:id="@+id/checkbox0"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:padding="5dip"/>

<CheckBox
    android:id="@+id/checkbox1"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:padding="5dip"/>
      .
      .
      .
<CheckBox
    android:id="@+id/checkbox50"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:padding="5dip"/>

You can do something like this to "findViewById" using a few lines instead of writing 50 "findViewById" lines:

CheckBox[] cb = new CheckBox[51];
for (int i = 0; i < 51; i++) {
        String idCheckBox = "checkbox"+i;
        cb[i] = (CheckBox) findViewById(YourActivity.this.getResources().getIdentifier(idCheckBox, "id", getPackageName()));
    }

where "YourActivity.this" refers to the context.

0

1) What for are there 50+ checkboxes?

If you have a list with checkboxes you should use ViewHolder to store info about each row.

2) Try to avoid findViewById each time when you need an item.

findViewById is an expensive operation so you should cache you items (for this very purposes ViewHolder was created).

dilix
  • 3,761
  • 3
  • 31
  • 55