2

Is there a way to generate R.drawable.... name on the fly? I want to set a background image with a dynamically generated name ( which is already usable as R.drawable.example_graphic)

So i want to find a way to assign a String to $ABC -> btn.setBackgroundImage(R.drawable.$ABC);

I don't want to create a new drawable, i want to use the existing one.

frankish
  • 6,738
  • 9
  • 49
  • 100
  • For those who are having the same problem: I am one of the upvoters of the above comment. However, i found with @CommonsWare's help that those solutions may require a cache which can be done using the solution of G.BlakeMeike – frankish Mar 01 '13 at 14:59

2 Answers2

3

Yes. Drawables are constants at compile time: you know exactly what exists. So, in your Application object, create a map:

public static final Map<String, Integer> NAMED_RESOURCES;
static {
  Map<String, Integer> m = new HashMap<String, Integer>();
  m.put(KEY1, R.drawable.ABC);
  m.put(KEY2, R.drawable.DEF);
  // ...
  NAMED_RESOURCES = Collections.unmodifiableMap(m);
}

now you can:

btn.setBackgroundImage(Application.NAMED_RESOURCES.get($ABC));

Kheldar
  • 5,361
  • 3
  • 34
  • 63
G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40
  • thank you for sharing this idea, however i have many resources (for example country flags), so it may not be good to use this solution for my case. – frankish Mar 01 '13 at 14:51
  • NP. Getting pipped by Mark is just part of participating in StackOverflow ;-) – G. Blake Meike Mar 01 '13 at 15:09
1

i have found the solution, as @CommonsWare has shared.

getContext().getResources().getIdentifier("flags_"+country, "drawable","mypackage")

However, it may require cacheing as it uses reflection.

So, creating a static HashMap to keep the ResourceName and it's result from getIdentifier function (integer) seems to be a good idea; further usages for the same ResourceName will just get the value from HashMap instead of using the reflection again.

frankish
  • 6,738
  • 9
  • 49
  • 100