Imageview - Defining Drawable by path

Asked

Viewed 1,127 times

2

Hello I’m starting on Android and I’m with a small project that would be a memory game. So to "shuffle the cards" I created a function that stores in an array of integers called codimg numbers from 1 to 12 random and different. Inside the folder drawable I have 12 images that have the same name changing only the end 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 I have done wrong because it returns the error below for all images, they are not found.

.jogodamemoria E/Bitmapfactory Unable to Decode stream: java.io.Filenotfoundexception: /app/src/main/res/drawable/img11.png: open failed: ENOENT (No such file or directory)

The path and exactly how it appears.

I hope you can help me, thank you!

1 answer

4


My suggestion for this case is to use the API of Resources to do so. Given the name of Resource it is possible to recover your identifier with 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.