0

in my android application there is group of buttons.i have given them id as b1,b2,b3... and using random function i'm generating a number and by using that number i'm changing button image. ex. if random number is 6.then i want to change image of button whose id is b6. how can i create id b6 using integer 6 and b and perform operations on that button.

    String id;
    Random rand=new Random();
int num=rand.nextInt(9)+1;
id="b"+num;

but in android id of button is not in string format

yuva ツ
  • 3,707
  • 9
  • 50
  • 78
  • 1
    Put your button resource ids into an array and then use your random number to select one of the array elements. – Squonk Jan 28 '13 at 07:39
  • i tried it.Drawable id[]={b1,b2,b3,b4,b5,b6,b7,b8,b9}; Drawable a = id[num].getBackground(); if(getResources().getDrawable(R.drawable.happy).equals(a)) but1.setBackgroundResource(R.drawable.happy); – yuva ツ Jan 28 '13 at 07:56
  • id[num].getBackground(); giving an error – yuva ツ Jan 28 '13 at 07:57
  • of course - it's an int! you want to do `getBackground` on the button, not its ID. to do this you must find it by ID using `findViewById(id[num]).getBackground()`. – andr Jan 28 '13 at 08:00

2 Answers2

1

You can simply declare an array with all the button IDs like that:

int[] buttonIds = new int[] {R.b1, R.b2, ...};

and use it to access the ID of a random button:

num = rand.nextInt(buttonIds.length);
int buttonId = buttonIds[num];
findViewById(buttonId).doSomething();

But it'll be tedious if the number of buttons becomes large or isn't constant. But for small numbers that seems fast and simple.

andr
  • 15,970
  • 10
  • 45
  • 59
0

The Resources class has this method:

public int getIdentifier (String name, String defType, String defPackage) 

Have a look at it.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
android2013
  • 415
  • 2
  • 5
  • also similar http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string http://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-ressource-name – android2013 Jan 28 '13 at 07:42