Issue
I'm making a puzzle app and I'd like to allow for multiple different configurations of the puzzle, including different images being used. Consider a resource name like this:
-drawable
-ImageResource1__puzzleType1__picture1
-ImageResource2__puzzleType2__picture1
etc.
Ideally I'd like to be able to reference this dynamically like so:
static final String IM1 = "ImageResource1__"
static final String puz1 = "puzzleType1__"
mImage.setDrawable(R.drawable.IM1 + puz1 + picture1)
Is this even possible?
Solution
It took a while but I finally found this information. The trick is to use Resources.GetIdentifier(); and piece together the name of the resource you are attempting to access as a string. The final result looks something like this:
String Package_Name = getBaseContext().getPackageName();
Resources mResources = getBaseContext().getResources();
PIC1 = mResources.getIdentifier(currentPicture + currentSize + "pc_1", "drawable", Package_Name);
PIC2 = mResources.getIdentifier(currentPicture + currentSize + "pc_2", "drawable", Package_Name);
Note: Now you can simply insert getBaseContext().getPackageName(); and getBaseContext().getResources(); where their identifiers are used but this adds two unnecessary method calls past the first variable you assign.
Since it isn't clear I named my picture resources in a template of genre_size_number. Ex: StarTrekEmblem_Large_pc_1. currentPicture holds a String such as StartrekEmblem_ whereas currentSize holds a string such as Large_. I could have used a loop to add the 1 or 2 after the pc_ but that again would have added unnecessary overhead to the program.
Final Note: "drawable" indicates the resource type you're variable points to. I point this out because the example I found used "string". In a particularly magnificent display of boneheadedness I assumed this was to indicate the TYPE of the variable you were attempting to store this in. As you can guess I did quite the run around figuring said error out.
Answered By - Brandon Thompson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.