Issue
I have an ImageView and I want it to display an image from my drawable folder based on the value of a number. I have a collection of images of playing cards in my drawable folder and I'm making a game where each card represents a number from 1 to 52. To represent this, I made a hashmap that links each number from 1 to 52 to a string which is the full name of the png file in my drawable folder. Now I need to find a way to use this key-value link in my hashmap to display a card in my ImageView depending on what my number variable is. The issue I've run into is that I don't know how to use the string value from the hashmap to access the image.
The statement that changes the image should look like this
dealt2.setImageResource(R.drawable.clubsace);
Where dealt2 is the ImageView variable.
I've checked and this works, but what I'm trying to do is something like:
dealt2.setImageResource(R.drawable.cards.get(1));
Where cards is my hashmap and cards.get(1) will return the string "clubsace.png". I don't know if there is a way to turn this string into something that can fit into that statement
Solution
dealt2.setImageResource(R.drawable.clubsace);
is equivalent to the following:
dealt2.setImageResource(dealt2.getResources().getIdentifier("clubsace", "drawable", dealt2.getContext().getPackageName()));
And please don't forget to remove .png
from the hashmap
Answered By - Vlad Guriev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.