Imageview - Defining Drawable by Path Path

2

Hello I'm starting on Android and I'm having a little project that would be a memory game. So for "shuffling the cards" I have created a function that stores in an array of integers called codimg numbers from 1 to 12 random and different. Inside the drawable folder I have 12 images that have the same name, changing only the ending with a numbering. I also have an array of ImageView called images

To set the images I have used the lines below

for (i = 0; i <= codimg.length; i++) {

           File file = new File("/app/src/main/res/drawable/img" + codimg[i]+".png");

           imagens[i].setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
       }

However something has been done wrong since it returns the error below for all images, they are not found.

.emptymask E / BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /app/src/main/res/drawable/img11.png: open failed: ENOENT (No such file or directory) / em>

The path is exactly as it appears.

I hope you can help me, grateful!

    
asked by anonymous 24.05.2015 / 17:42

1 answer

4

My suggestion for this is to use the Resources API to do this. Given the resource name you can retrieve your identifier using the method below:

public int getImageDrawableResId(String imageId) {
    Resources resources = getResources();
    return resources.getIdentifier(imageId, "drawable", getPackageName());
}

To use just call by passing the name of drawable :

for (i = 0; i <= codimg.length; i++) {
    int drawableId = getImageDrawableResId("img" + codimg[i]);
    Drawable dr = getResouces().getDrawable(drawableId);

    imagens[i].setImageDrawable(dr);
}
    
24.05.2015 / 17:49