Dynamically initialize array of objects when using findViewById
<p>I'm very new to both java and Android.</p>

<p>If you have a better title for my question i'm all ears.</p>

<p>I'm doing an app that has led lights, i have wrapped ImageViews in a class i've created my self. I initialize my leds like this:</p>

<pre><code>lightRig = new Led[] {
        new Led((ImageView) findViewById(R.id.imageView20), R.drawable.green_on_10, R.drawable.green_off_10),
           ...
           new Led((ImageView) findViewById(R.id.imageView1), R.drawable.green_on_10, R.drawable.green_off_10),
}
</code></pre>

<p>It hurts my eyes to hard code 20 leds like this and i'd like to do it more dynamic. My problem is that i need to refer to the R.id.imageViewXX in order to associate it with my Led, and <strong>i</strong> can't find another way than the one i've done above. Please advice a newbie.</p>

<p><strong>Update</strong>: There should be 20 leds on a single line, acting like a progress bar. Starts with green leds and then ends with red leds.</p>

<p>I do agree with the comment from Lars that i perhaps should take a different approach. It feels like i should. I just don't know how.</p>

<p>I've taken this approach based on comments and other sources:</p>

<pre><code>  while(i &lt; numberOfImageViews - 1) {
      //Through reflection we can get the IDs, but its very expensive.
       int id = getResources().getIdentifier("imageView" + (i+1), "id", getPackageName());
       if (id &gt; 0) {
           switch(i) {
            case 0  : drawableOn = R.drawable.green_on_10;
                      drawableOff = R.drawable.green_off_10;
                      break;
            case 5  : drawableOn = R.drawable.yellow_on_10;
                      drawableOff = R.drawable.yellow_off_10;
                      break;
            case 10 : drawableOn = R.drawable.orange_on_10;
                      drawableOff = R.drawable.orange_off_10;
                      break;
            case 15 : drawableOn = R.drawable.red_on_10;
                      drawableOff = R.drawable.red_off_10;
                      break;
           }
           lightRig[i] = new Led ( (ImageView) findViewById(id), drawableOn, drawableOff );
      }
      i++;
  }
</code></pre>
