I want to use position (returned from a gridview for e.g.) or a similar numeric integer to do various things, e.g. create a sprite, or in any command that wants something other than a number, e.g. I want to use something like:
sprites.add(createSprite(R.drawable.image(position));
, where createSprite creates a sprite using the image supplied,
instead of:
if (position == 1) {sprites.add(createSprite(R.drawable.image1);}
if (position == 2) {sprites.add(createSprite(R.drawable.image2);}
...etc
There is an easy solution for strings:
Most efficient method to use position to open a .java
but what about for situations like this one?
The disadvantage of the suggestion from @abhinav8, which definitely isn’t a bad one by the way, is that you don’t get the dynamic loading from different size/density buckets for free. Alternatively, you could just declare an array containing the resource ids and iterate through that.
A a last resort, I’d also like to point out a method that the
Resourcesclass provides:getIdentifier(String name, String defType, String defPackage).This allows you to dynamically look up a resource identifier by name, which means you could use it in a way similar to what is being suggested in the linked Q&A.
However, there’s a catch, that is added as note in the method’s documentation. It says:
That basically means: don’t use it unless you really have to, and even then, use it scarcely. Just thought I should point out the method for completeness though.