简体   繁体   中英

Java setImageResource

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

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

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