1

I apologize beforehand if this is an easy question, however i am not able to find something relevant.

What i want to do:

Let's say i have a string: My name is -variable- and I am -variable- years old. I live -variable- bla bla bla.

How do i declare this on XML?

Any guidelines and directions for more reading regarding this topic are appreciated.

Thanks a lot and in advance

thanosChatz
  • 135
  • 2
  • 11

3 Answers3

2

You can use xliff annotations in your string.

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string id="foo">
      My name is <xliff:g id="name" example="Andy Droid">%s</xliff:g> and I am <xliff:g id="age" example="5">%d</xliff:g> years old. I live in <xliff:g id="city" example="Paris">%s</xliff:g>. blabla
    </string>
</resources>

And your reference it in your layout with android:text="@string/foo"

Android Studio will display nicely

My name is (Andy Droid) and I am (5) years old. I live in (Paris). blabla

Of course, you also need a code replacement

final TextView tv = (TextView) findViewById(R.id.bar);
String name = ...;
int age = ...;
String city = ...;
tv.setText(getString(R.string.foo, name, age, city));
rds
  • 26,253
  • 19
  • 107
  • 134
  • There is even support in Android Studio http://stackoverflow.com/questions/11331809/improving-android-string-resources-with-xliff/19307864#19307864 – rds Nov 12 '14 at 15:21
1

You can add this string

<string name="example">My name is %s and I am %d years old. I live %s bla bla bla</string>

in your strings.xml file.

And in your code :

TextView tv = (TextView) findViewById(R.id.tv1);
String name = "";
int age = 0;
String city = "";
tv.setText(String.format(getString(R.id.example),name,age,city));
Silvia H
  • 8,097
  • 7
  • 30
  • 33
-1

EDIT: Okay sorry, this is apparently bad practice. It will work, but I'm sure there are better solutions. I just haven't had to do anything like this yet.

It sounds like you want to set the string programmatically. There may be a more elegant solution, but you may have to store each of the strings separately and then combine them in your code.

<string name="my_name_is">My name is </string>
<string name="and_i_am"> and I am </string>
<string name="years_old"> years old.</string>

And in your code

String name = "Bill";
String age = "12";
String str = getString(R.id.my_name_is) + name + getString(R.id.and_i_am) + age 
    + getString(R.id._years_old);

Output: "My name is Bill and I am 12 years old."

This answer shows how you can reference one string from another string in xml, but I don't think that's what you're looking for.

Community
  • 1
  • 1
NSouth
  • 5,067
  • 7
  • 48
  • 83
  • 1
    Holy Crap! Don't do that! It's a worse practice for internationalisation. – rds Nov 12 '14 at 15:19
  • Sorry, I haven't had to do this before so I just put down what would work. I've updated my answer to indicate it's not a good approach. – NSouth Nov 12 '14 at 15:27