gurehbgui
gurehbgui

Reputation: 14694

How to pass Data to the getText?

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?

Upvotes: 0

Views: 475

Answers (4)

Hbibna
Hbibna

Reputation: 568

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

Upvotes: 1

Badgerati
Badgerati

Reputation: 171

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!");

Upvotes: 1

Selvin
Selvin

Reputation: 6797

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>

Upvotes: 3

Anthony Atkinson
Anthony Atkinson

Reputation: 3248

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);

Upvotes: 0

Related Questions