0

I have the following String ressource:

<string name="foo">This is a {0} test. Hello {1}</string>

Now I want to pass the values 1 and foo when calling:

getResources().getText(R.string.foo)

how to make this? Or is it not possible?

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

4 Answers4

3

getResources().getString(R.string.foo, 1, "foo"); but string should be using string format ... so your string in string should looks like:

<string name="foo">This is a %d test. Hello %s</string>
Selvin
  • 6,598
  • 3
  • 37
  • 43
1

I'm not too sure if Java has something like this inbuilt. I did once write a method that would do the exact thing you're looking for, however:

public static String format(String str, Object... objects)
{
    String tag = "";

    for (int i = 0; i < objects.length; i++)
    {
        tag = "\\{" + i + "\\}";
        str = str.replaceFirst(tag, objects[i].toString());
    }

    return str;
}

And this would format the string, to replace the '{i}' with the objects passed; just like in C#.

example:

format(getResources().getString(R.string.foo), "cool", "world!");
Badgerati
  • 171
  • 3
1

You can do it this way :
string name="foo">This is a %d test. Hello %s string>
with
getString(R.string.foo, 1, "foo");

Source : Are parameters in strings.xml possible?

You can find more information on formatting and formats here : http://developer.android.com/reference/java/util/Formatter.html

Community
  • 1
  • 1
Hbibna
  • 568
  • 7
  • 11
0

I believe that the simplest way to do what you're wanting is to save the line of code you have to a variable then use the Java String replace() function.

String fooText = getResources().getText(R.string.foo);
fooText = fooText.replace("{0}", myZeroVar);
fooText = fooText.replace("{1}", myOneVar);
Anthony Atkinson
  • 3,101
  • 3
  • 20
  • 22