0

I have 52 images of a deck of cards in my Drawable folder, with .png format.

I want to modify my android:src attribute of an ImageView, but using a var which saves the name of my image name. For example.

String nameOfCard="two_of_diamonds"; // and as I said I have an Image called two_of_diamonds in my Drawable folder

I tried several ways but I didn´t find the correct one. If I use: imageview.setImageResource(int) I need an int not a String reference.

Any idea? Thanks!

4 Answers 4

2

Use the following code to access drawable resources using name:

    Resources resources = getResources();
    final int resourceId = resources.getIdentifier("two_of_diamonds",
            "drawable", getPackageName());

    imgView.setImageResource(resourceId);
Sign up to request clarification or add additional context in comments.

1 Comment

aaah you guy are quick and clear. nº1 :) Thaank you so much, it was the last step in my app, I´m so happy now jj
0

Use getIdentifier()

public int getIdentifier (String name, String defType, String defPackage)

This will return the id. Use the id to set image resource for imageview.

For example,

int id = getResources().getIdentifier(nameOfCard,"drawable",getPackageName());
imageview.setImageResource(id);

Comments

0

Create an Object of Image like

class Image{
    String Name;
    int Id;
    public Image(String Name,int id){
        this.Name=Name;
        Id=id;
    }

}

Create an Array of Images

Image[] images = {new Image("name",R.drawable.name_of_image),...);

When Setting image use

for(Image i: images){
    if(i.Name.equals("desired")){
        imageview.setImageDrawable(i.Id);
    }
}

There must be a better approach to the problem than this. It is a very basic one.

Comments

0

I needed this in Kotlin and used Deven's answer. It became:

    // THIS IS KOTLIN, NOT JAVA
    var diceRoll = dice.roll()
    var diceRoll2 = dice.roll()
    // Update the screen with the dice roll
    diceImage.setImageResource(getMyResource("dice_" + diceRoll))
    diceImage2.setImageResource(getMyResource("dice_" + diceRoll2))

fun getMyResource(imageName: String):Int{
    val resources: Resources = resources
    val resourceId: Int = resources.getIdentifier(
        imageName,
        "drawable", this.packageName
    )
    return resourceId
}

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.