-3

In my android app, I have 9 buttons with the following reference:

R.id.button1;
R.id.button2;
....
R.id.button9

If I have an int value, lets say int i which holds the button number, is there a simple way for me to call the reference such as

String s = "R.id.button" + Integer.toString(i);
Button btn = (Button) findViewbyId(s);

My code is gettting way to verbose by doing 9 if checks. Thanks!

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
David
  • 207
  • 4
  • 13

1 Answers1

0

You can try like this to get the Button Object from String value,

String s = "button" + i;
int viewId = getResources().getIdentifier( s, "id", getPackageName());

Button btn = (Button) findViewById(viewId);
Muthukrishnan Rajendran
  • 10,596
  • 2
  • 29
  • 39