Android findViewByID programmatically

I have 4 button seen below sequentially numbered in my layout file. In my code i want to get in a loop the advert that corresponds to the position we are in the loop e.g for the second time around in the loop i would get advert2 back.

Can anyone help. Thanks

Button advert1 = (Button) findViewById(R.id.advert1);
Button advert2 = (Button) findViewById(R.id.advert2);
Button advert3 = (Button) findViewById(R.id.advert3);
Button advert4 = (Button) findViewById(R.id.advert4);

Upvotes: 1

Views: 1644

Answers (1)

MAC
MAC

Reputation: 15847

Button[] btnArr= new Button[4];

int[] arr = new int[4];

arr[0]=R.id.advert1;
arr[1]=R.id.advert2;
arr[2]=R.id.advert3;
arr[3]=R.id.advert4;

for(int i=0;i<4+i++)
{
   btnArr[i]=(Button) findViewById(arr[i]);
}

Upvotes: 3

Related Questions