2

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.

2

4 Answers 4

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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()))); 
        }

Comments

0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.