10

I'm trying to combine a static "hard coded" string with one referenced from strings.xml for string array items.

The goal is to have a dynamic metrics list where the number is the same for all languages, but the metrics text value may change by language, something like this:

<string-array name="interval_labels">
    <item>30 @string/second</item>
    <item>1 @string/minute</item>
    <item>5 @string/minute</item>
    <item>10 @string/minute</item>
    <item>15 @string/minute</item>
    <item>30 @string/minute</item>
    <item>60 @string/minute</item>
</string-array>

Right now, if I remove the numbers before the @string/... references, it works well (as mentioned here), but I was wondering whether there is a way to retrieve the referenced string and concatenate it to the "hard coded" one.

Community
  • 1
  • 1
Tõnis Pool
  • 185
  • 1
  • 3
  • 8
  • http://stackoverflow.com/a/2865276/1085128 seems to indicate that it is at least almost possible. Possibly even fully possible. – mako Dec 31 '13 at 19:22
  • By defining an XML entity it's possible. I used this answer: http://stackoverflow.com/questions/3656371/dynamic-string-using-string-xml/24903097#24903097 – Andrew Nov 02 '15 at 02:18

3 Answers3

6

Sorry, no such syntax is supported by Android resource files.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • if it's so, it's sad, guess I'll have to move the digits to strings.xml as well. – Tõnis Pool Nov 20 '11 at 18:50
  • Using XML entities it is possible to reference the same string multiple times in an Android xml file like strings.xml. See my answer below. – Andrew Nov 02 '15 at 02:31
1

Using XML entities it's possible.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
  <!ENTITY mintues "minutes">
  <!ENTITY minute "minute">
  <!ENTITY seconds "seconds">
]>

<resources>
  <string-array name="interval_labels">
    <item>30 &seconds;</item>
    <item>1 &minute;/item>
    <item>5 &minutes;</item>
    <item>10 &minutes;</item>
    <item>15 &minutes;</item>
    <item>30 &minutes;</item>
    <item>60 &minutes;</item>
  </string-array>
</resources>

I used this answer: dynamic String using String.xml?

Community
  • 1
  • 1
Andrew
  • 1,057
  • 11
  • 19
-1

There is a way of sort-of getting this effect, by defining the string resource with a place holder and using String.format() style overload of getResourses().getString() in the code behind:

In string.xml

<string name="secs">%1$d seconds</string>

In activity_layout.xml

<TextView android:id="@+id/secs_label" />

In TheActivity.java

((TextView)findViewByID(R.id.secs_label)).setText(getResources().getString(R.string.secs, 25));
Jonathan Twite
  • 932
  • 10
  • 24