Reputation: 43
I have a little card game. In an ArrayList I add the 52 cards:
ArrayList<String> liste = new ArrayList<String>();
and fill it with this:
for (int n=1; n<14; n++) {
liste.add("d" +n); //diamonds
liste.add("c" +n); //clubs
liste.add("s" +n); //spades
liste.add("h" +n); //hearts
}
To draw a card I use this code:
private void drawCard() {
if (liste.size()!=0) {
Collections.shuffle(liste);
kort.setText("" + liste.get(0));
int i = liste.size();
cardsLeft.setText("" + (i - 1));
cardImage.setImageResource(R.drawable.XXX);
liste.remove(0);
}
else kort.setText("No more cards in deck");
}
In my drawable folder I have 52 pictures of cards with the same name as the names in the ArrayList. When the program draw eg. d2 i need to set the ImageView cardImage to image d2 from the drawable folder as well:
cardImage.setImageResource(R.drawable.d2);
Need help to how I change the imageview to match the drawn card
Upvotes: 0
Views: 60
Reputation: 48242
You can do:
public static int getDrawableId(Context ctx, String name) {
return ctx.getResources().getIdentifier(name, "drawable", ctx.getPackageName());
}
cardImage.setImageResource(getDrawableId(YourActivity.this, "d2"));
Upvotes: 1