Looping through numerous Button variables

115 views Asked by At

I have 50 Buttons coded like this:

button_list.set(0,(Button) findViewById(R.id.button0));
button_list.set(1,(Button) findViewById(R.id.button1));
button_list.set(2,(Button) findViewById(R.id.button2));
button_list.set(3,(Button) findViewById(R.id.button3));
button_list.set(4,(Button) findViewById(R.id.button4));
button_list.set(5,(Button) findViewById(R.id.button5));
button_list.set(6,(Button) findViewById(R.id.button6));
button_list.set(7,(Button) findViewById(R.id.button7));
button_list.set(8,(Button) findViewById(R.id.button8));
button_list.set(9,(Button) findViewById(R.id.button9));
button_list.set(10,(Button) findViewById(R.id.button10));
button_list.set(11,(Button) findViewById(R.id.button11));
button_list.set(12,(Button) findViewById(R.id.button12));
button_list.set(13,(Button) findViewById(R.id.button13));
button_list.set(14,(Button) findViewById(R.id.button14));
button_list.set(15,(Button) findViewById(R.id.button15));
.
.
.

How can I put this all in a loop?

When I run the below code I get NullPointerExceptions, I guess meaning the Buttons are not recognized when I attempt to use findViewById. Does anyone know what is wrong with the following code and how I can fix it?

Button[] bttn = new Button[50];

String ids[] = new String[50];
for(int i=0; i<50; i++)
{
   ids[i] = "button" + Integer.toString(i);
}

for(int i=0; i<50; i++)
{
   int resID = getResources().getIdentifier(ids[i], "id", "your.package.name");
   bttn[i] = (Button) findViewById(resID);
}


for(int i=0; i<50; i++)
{
   button_list.set(i, bttn[i]);
}
1

There are 1 answers

4
zgc7009 On

You can do it in a single loop

Button[] buttons = new Button[50];
for(int i = 0; i < buttons.length; i++){
    button[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", getPackageName());
    buttonList.set(i, button[i]);   // if your list is already built
    //buttonList.add(button[1]);    // if you are building your list
}

I use getPackageName() as I assume you are in an Activity, if that is not the case you need to get a reference to the context and use context.getPackageName(); This goes the same for the getResources() call as it also needs a reference to your context.