sanogueralorenzo
sanogueralorenzo

Reputation: 25

Android number1.setImageResource(R.drawable.n+"1"); Explanation

Avoid this if possible. Step back and rethink if you really need to do it this way as it is an expensive operation and probably there are better ways of doing it.

Upvotes: 0

Views: 182

Answers (3)

ekchang
ekchang

Reputation: 939

If you will only be using those 9 drawables, just create an array to hold the resource ID values of those drawables.

static final int[] RESOURCE_IDS = {
    0, // empty value so that i = 1 corresponds to R.drawable.n1
    R.drawable.n1,
    ...
    R.drawable.n9
};

Random rand = new Random();
int resourceId = RESOURCE_IDS[rand.nextInt(9)+1]; // random integer from 1-9
mImageView.setImageResource(resourceId);

Upvotes: 1

Ertyguy
Ertyguy

Reputation: 666

The method setImageResource is expecting an integer that is generated and stored in the R file, so appending a String to the method is not going to work.

Luckily, Android does provide a method to use called getIdentifier

getResources().getIdentifier("n1", "drawable", this.getPackageName());

This method is slow though, so if you are calling it a bunch of times, it may be better to instead load all the resources as bitmaps at the beginning and then set the ImageView resource to be whatever bitmap you need at the time

Bitmap[] numbers = new Bitmap[9]   
for(int i=1; i<=9; i++) {
    numbers[i] = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(("n"+i), "drawable", this.getPackageName()););
}

Then you can make a method to call

private void setNumber(int i) {
    image.setImageBitmap(numbers[i]);
}

Upvotes: 1

Randyka Yudhistira
Randyka Yudhistira

Reputation: 3652

You can use the method to convert string into int identifier:

public static int getStringIdentifier(Context context, String name) {
    return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
}

Pass in an activity as context parameter (or any other Context instance). Then you can use the identifier as usual with getString() method.

Note that conversion from string to identifier uses reflection and thus can be not that fast, so use carefully. Refer to : This SO post

Example use : number1.setImageResource(getStringIdentifier(this,String.valueOf(n+rnd)));

Upvotes: 2

Related Questions