I was trying to save time by using a for loop to initialize all the sprites i wanted on screen. I had a couple of images on my drawable folder. So I renamed them accordingly. I wanted to concatenate the i to the expression, then it had to be called/invoked somehow!
At first I thought about doing this:
Integer.parseInt("R.drawable.scoredisplay" + i)
Then, of course you cant parse that into an integer, also the result of that expression returns an integer anyway. How can I make the concatenation of the expression with i and then call it? is it possible?
It’s possible, you need to do the following:
Where the first parameter is the id as
Stringof theViewyou want to get, the second one is the type of resource in this case “drawable”, and the third one the package name which we obtain also from the context, callinggetPackageName()method.Then afterwards you can get the view with the following code:
Casting the string to an integer as you were thinking makes no sense, since the id is not a string (although it has a workaround like I’m showing you).
Update
Since you are using this code outside of an
Activityclass the calls to theContextmethods are not valid. You need to create a way of accessing the Activity Context from outside of the activity (you mention calling.getContext()from your class, but that will get that classes context, not the activity). A way of achieving this would be modifying your constructor, lets say you have a class namedmyClass:The last part in ensuring you are passing your value correctly from your
Activity, you should see something similar to this somewhere in your code:Since we now have a constructor, or have modified the existing one, you can add
thisto pass the activity context right into your game or whatever class your creating: