Dynamic String Resources for Android

in my application, I am making a web request that returns some result code, for example. 105. I have string resources that look like this.

<string name="r105">O.K.</string>
<string name="r106">Something went wrong.</string>
<string name="r333">Fatal error.</string>

Now i want to do something like this

Toast.makeText(parent.getApplicationContext(),
        parent.getString(R.string.r+resultCode), Toast.LENGTH_LONG).show();

and r+resultCode- resource identifier.

This does not work. Any idea how to do this?

+5
source share
4 answers

Try it in a getResources().getIdentifier(name, defType, defPackage)simple way.

Toast.makeText(this, getResources().getIdentifier("r"+resultcode, "string", 
getPackageName()), Toast.LENGTH_LONG).show();
+13
source

You can do this using getResources().getIdentifier(name, defType, defPackage). Something like that:

// Assuming resultCode is an int, use %s for String
int id = getResources().getIdentifier(String.format("r%d", resultCode), 
                                      "string", getPackageName());
String result = getString(id);
+4
source

, , . parent.getApplicationContext() .

String str = getString(R.string.r)+resultCode;

        Toast.makeText(getApplicationContext(),
                str, Toast.LENGTH_LONG).show();
0

An easy way to get a resource identifier from a string. Here, resourceName is the name of the ImageView resource in the transferable folder, which is also included in the XML file. I get "id", you can use "string".

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
0
source

All Articles