yuva ツ
yuva ツ

Reputation: 3703

getting id of button and performing operations in android

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

Upvotes: 0

Views: 119

Answers (2)

android2013
android2013

Reputation: 425

The Resources class has this method:

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

Have a look at it.

Upvotes: 0

andr
andr

Reputation: 16054

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.

Upvotes: 1

Related Questions