Skip to content Skip to sidebar Skip to footer

Use Dynamic R Strings In Android

I'm having a problem using strings stored in my strings.xml, I have a wide list of strings stored there. They are very useful for me because I'm using them to translate my program.

Solution 1:

There's a way 10 times faster than regular android method "getIdentifier" to get the value from not only string but also drawable or any other resource existing in the R file in a very simple manner using reflection as follows:

try {
        //Get the ID
        Field resourceField = R.string.class.getDeclaredField("yourResourceName");
        //Here we are getting the String id in R file...But you can change to R.drawable or any other resource you want...int resourceId = resourceField.getInt(resourceField);

       //Here you can use it as usualString yourString = context.getString(resourceId);

    } catch (Exception e) {
        e.printStackTrace();
    } 

Hope this helps.

Regards!

Solution 2:

Use a two-step process to find the id to load. First use Resources.getIdentifier(), for example:

intid = getResources().getIdentifier("yellow", "string", getPackageName());

Then, after checking the id is not zero (which indicates it could not find the resource), use the id to get a string like normal:

String colour = getString(id);

Solution 3:

String mystring = getResources().getString(R.string.yellow);

Post a Comment for "Use Dynamic R Strings In Android"