Steven Osborn
"I would love to change the world, but they won't give me the source code".

Accessing Android Resources By Name at Runtime

November 27, 2007 – 4:30 pm

Here’s a little snippet I wrote to access resources in R.java during runtime. It just uses reflection to get the filed names of the objects in the R class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class RR {
    public static Drawable getDrawable(Context context, String name) {
        Class<R.drawable> c = R.drawable.class;
        Drawable d = null;
        Field f;
        int i = 0;
 
        try {
            f = c.getField(name);
            i = f.getInt(f);
            d = context.getResources().getDrawable(i);
        } catch (Exception e) {
            Log.e("RR",e.toString());
        }
        return  d;
    }
 
    public static String getString(Context context, String name) {
        Class<R.string> c = R.string.class;
        String s = null;
        Field f;
        int i = 0;
 
        try {
            f = c.getField(name);
            i = f.getInt(f);
            s = context.getResources().getString(i);
        } catch (Exception e) {
            Log.e("RR",e.toString());
        }
        return s;
    }
 
}

With this class you could access resources at run time just like the example below. I found this extremely useful in one scenario where I switch Drawable resources out at run-time based on user interaction.

1
2
3
   // inside any view/action
   Drawable icon = RR.getDrawable(this,"myicon");
   String mystring = RR.getString(this,"icon_name");

Feel free to use the code above in your projects. I would really like to see your hacks and improvements for it.

You must be logged in to post a comment.