简体   繁体   中英

How to assign Image Resource to ImageView with String in Android

I am trying to create a routine that will assign a card image to an ImageView without using something like this: R.drawable.card_10clover. I would prefer to use a string, but the way I'm doing it doesn't work.

String imgRes = "R.drawable.card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
card.setImageResource(imgRes);

Unfortunately setImageResource only takes an int. Please help.

Thank you, Jack Blue

Use getIdentifier (String name, String defType, String defPackage); Your imgRes does not need the prefix R.drawable

String imgRes = "card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
int resourceId = getResource().getIdentifier (imgRes, "drawable", "com....");
card.setImageResource(resourceId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM