0

I created nine Button view in the main.xml and named it to Button1, Button2... Button9.. Then in my code I created an ArrayList of Button and its obvious that this array of buttons will hold my Button in the main.xml and in my current knowledge that to get the Button in my main.xml I need to use the findViewById method and basically I need to loop the array to get the button

ArrayList<Button> buttons;
int MAXBTN = 9;
for( int i = 0; i < BTN; i++ )
{
    // Code here to use the findViewById method to get the button
}

And my problem is that I need to pass R.id.Button1 .. R.id.Button3 to the findViewById method, but I need to loop this. Is there anyway I can pass a counter in the findViewById while loop?

Please advise.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
domlao
  • 15,663
  • 34
  • 95
  • 134

2 Answers2

1

You can try this.

ArrayList<Button> buttons;
int MAXBTN = 9;
for( int i = 0; i < BTN; i++ )
{
    String buttonID = "Button" + i+1 ;
    int resID = getResources().getIdentifier(buttonID, "id", "packageName");
    buttons.get(i) = ((Button) findViewById(resID));
}
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
1

I think there is already a same question asked for this check this


Its always better to search first before asking

Community
  • 1
  • 1
MKJParekh
  • 34,073
  • 11
  • 87
  • 98