16

Android allows to create aliases of resource strings like:

<resources>
 <string name="foo">somestring</string>
 <string name="bar">@string/foo</string>
</resources>

by which the resource "bar" becomes an alias for the resource named "foo".

What I would for my app is a possibility to combine an existing resource prefix with different suffixes, i.e. to extend it like:

<resources>
 <string name="foo">foo</string>
 <string name="bar">@string/foo+bar</string> 
 <string name="else">@string/foo+else</string> 
</resources>

where the resource "bar" would yield the string "foobar". Its clear that '+' doesn't work here but is there some other option to achieve such a string concatenation, so that one could define a bunch of string resources that have a common prefix?

I realize of course that I could do such resource string concatenation at runtime but defining them statically in the resources would seem so much more elegant and simpler.

Michael

mmo
  • 3,897
  • 11
  • 42
  • 63

2 Answers2

16

No, it's not possible. You can just use <string name="bar">This is my %s</string> and then use String.format() in your app to fill in the variable with for example

getResources().getString(R.string.foo);
Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
  • 2
    The string resulted by combining those 2 will be `String.format(getResources().getString(R.string.bar), getResources().getString(R.string.foo))` – Paul Feb 27 '16 at 18:49
6

I know it's late, but anyways now you can do so by using this library I've created: https://github.com/LikeTheSalad/android-stem

It will concat all of the strings you want to at build time and will generate new strings that you can use anywhere in your project as with any other manually added string.

For your case, you'd have to define your strings like so:

<resources>
 <string name="foo">foo</string>
 <string name="bar">${foo} bar</string> 
 <string name="else">${foo} else</string> 
</resources>

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

<!-- Auto generated during compilation -->
<resources>
 <string name="bar">foo bar</string> 
 <string name="else">foo else</string> 
</resources>

These auto generated strings will keep themselves updated for any changes that you make to your templates and values. They also work with localized and flavor strings. More info on the repo's page.

César Muñoz
  • 535
  • 1
  • 6
  • 10
  • This does not work for me – amarradi Jul 05 '22 at 08:14
  • Sorry to heat it @amarradi, if you like I can try to help if you create an issue here and provide more info on what is it that doesn't work for you: https://github.com/LikeTheSalad/android-stem/issues – César Muñoz Jul 05 '22 at 09:41
  • This looks very interesting and I might be in a position to make use of this soon. I'm glad someone else has addressed my pain point already. – Richard Le Mesurier Oct 04 '22 at 11:27