How can I concatenate static strings with XML string resources?

佐手、 提交于 2019-12-10 02:43:28

问题


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.


回答1:


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




回答2:


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?




回答3:


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


来源:https://stackoverflow.com/questions/8203540/how-can-i-concatenate-static-strings-with-xml-string-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!