Reputation: 23
I am novice in android development.I am developing a game.It has 20 images with image names like num1,num2,num3..,num20.
For reading all these images i have done this in java
for ( int i=0 ; i<n ; i++)
{
imgarr[i] = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("images/"+(i+1)+".png"));
}
My question is how to do the same in android?
How to read all those images into bitmap array in simple for loop?
I know in android we can read an image into bitmap as fallows
img = BitmapFactory.decodeResource(getResources(), R.drawable.image_name);
Is there any way to read all those images in for loop?
Thanks.
Upvotes: 2
Views: 6116
Reputation: 96
define a array of image-id like this
int[] ImgArr = {R.drawable.image1, R.drawable.image2....};
Then you can iterate like this:
for ( int i=0 ; i<n ; i++)
{
img = getResources().getDrawable(ImgArr [n]);
}
Upvotes: 0
Reputation: 3497
You can do it this way:
for(int i = 0; i < count; i++){
try{
Class drawable = R.drawable.class;
Field f = drawable.getField("num" + i);
int id = f.getInt(null);
img = BitmapFactory.decodeResource(getResources(), id);
}catch(Exception ex){
}
}
But this is a bad way. You can use Assets folder.
Upvotes: 1
Reputation: 3340
You can construct a custom array which contains all the resource id of your image and using a for loop
for example:
int ids[] = new int[]{R.id.img1, R.id.img2};
for(int id : ids) {
img = BitmapFactory.decodeResource(getResources(), id);
}
Upvotes: 1
Reputation: 28484
DO like this way
List<Bitmap> imgList = new ArrayList<Bitmap>();
for ( int i=1 ; i<=n ; i++)
{
imgList.add(BitmapFactory.decodeResource(getResources(), getResources().getIdentifier("num" + i, "drawable", getPackageName())));
}
Upvotes: 0