Olegario López
Olegario López

Reputation: 443

how to set a variable imageview src?

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!

Upvotes: 0

Views: 3750

Answers (4)

TecBrat
TecBrat

Reputation: 3729

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
}

Upvotes: 0

Daksh Agrawal
Daksh Agrawal

Reputation: 923

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.

Upvotes: 0

Devendra
Devendra

Reputation: 3444

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

Upvotes: 2

Jyoti JK
Jyoti JK

Reputation: 2171

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

Upvotes: 0

Related Questions