3

In my Android app I'm using strings.xml for all texts. I have many situations where I use almost the same string,

e.g. "Name" and "Name:" - translation is the same only additional colon is difference.

Is there any other way to have these two string except creating two string items like this:

<string name="name">Name</string>
<string name="name2">Name:</string>
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3626048
  • 706
  • 4
  • 19
  • 52
  • i think it is not possible to have same id for the two different strings – A.s.ALI Sep 29 '16 at 07:19
  • Possible duplicate of [Reference one string from another string in strings.xml?](http://stackoverflow.com/questions/4746058/reference-one-string-from-another-string-in-strings-xml) – Anton Malyshev Sep 29 '16 at 07:21
  • You can try to declare one base string then create something like a string formatter class or method. Pass the base string to a method then return the formatted string. – Ace Siena Sep 29 '16 at 07:25
  • @AceSiena thanks, that's not a bad solution but I'm also creating string-array using reference to my strings so I can't use it in my Java code. Thou I'm gonna use it where I can. – user3626048 Sep 29 '16 at 07:31

2 Answers2

1

There is no way you can concatenate strings in the strings.xml file.

All you can do is specify the format,

<string name="name">Name</string>
<string name="string_with_colon">%s:</string>

Then pass the name programatically,

String.format(getString(R.string.string_with_colon), getString(R.string.name));
pratZ
  • 3,078
  • 2
  • 20
  • 29
  • thanks, that's not a bad solution but I'm also creating string-array using reference to my strings so I can't use it in my Java code. – user3626048 Sep 29 '16 at 07:30
1

Yes, you can do so without writing any Java/Kotlin code, only XML by using this small library I created which does so at buildtime: https://github.com/LikeTheSalad/android-stem

Usage

Based on your example, you'd have to set your strings like this:

<string name="name">Name</string>
<string name="name2">${name}:</string>

And then after building your project, you'll get:

<!-- Auto generated during compilation -->
<string name="name2">Name:</string>
César Muñoz
  • 535
  • 1
  • 6
  • 10