-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
  • 8,084
  • 8
  • 48
  • 62
David
  • 217
  • 4
  • 14

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
  • 11,122
  • 3
  • 31
  • 41