Use dynamic R strings in Android

旧巷老猫 提交于 2020-01-11 09:21:06

问题


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. However, now I want to choose between those strings dynamically and I don't know how to do it. It will be easier to understand with an example. Let's assume that I have the following strings:

<string name="red">Red</string>
<string name="blue">Blue</string>
<string name="green">Green</string>
<string name="yellow">Yellow</string>

And now let's assume that I have a function that passes me a string with a color, for example "yellow". Now I only have a solution for this, to make a very huge switch (very very huge, because I have lots of strings), I think that there must be an option to transform the output of my function into the right parameter. I mean, if I have a function that returns me "yellow", and I want to use R.strings.yellow, there must be a link between them. I don't know if maybe you could use any kind of reflection to achieve this.

Can you help me?


回答1:


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

int id = 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);



回答2:


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 usual
       String yourString = context.getString(resourceId);

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

Hope this helps.

Regards!




回答3:


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


来源:https://stackoverflow.com/questions/18707553/use-dynamic-r-strings-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!