2

Using Android Studio and I would like to know how to get "months" to pick up a string from xml string please. (Just learning android at the moment). Need to pick up from strings.xml as I need to translate that to another language.

else if (human_year == 0) {
        return Integer.toString(Math.round(human_month)) + " months";

output: years - which can be translated into Spanish (this is working have set up a button to translate) currently all words linked back to a string.xml are being translated. As this "months" is not attached to a string it is not being translated.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Muppet
  • 21
  • 1
  • Possible duplicate of [How to use Android quantity strings (plurals)?](https://stackoverflow.com/questions/41950952/how-to-use-android-quantity-strings-plurals) – Martin Zeitler Mar 31 '19 at 12:05
  • ^ it's not an exact duplicate, but it explains the combination of plurals and string format. – Martin Zeitler Mar 31 '19 at 12:06

2 Answers2

1

First declare "months" in

English strings (default locale), /values/strings.xml

<resources>
    <string name="myStringMonths">months</string>
</resources>

then for spanish

Spanish strings (es locale), /values-es/strings.xml:

<resources>
    <string name="myStringMonths">meses</string>
</resources>

then in your code take it as below:

else if (human_year == 0) {
        return  String.format("%d", Math.round(human_month)) + getString(R.id.myStringMonths);
android
  • 2,942
  • 1
  • 15
  • 20
0

Use a "Quantity String" for this.

Create a plurals.xml files in your Resources directory. Then populate it with something along the lines of:

<resources>
    <plurals name="months">
        <item quantity="one">%1$d month</item>
        <item quantity="other">%1$d months</item>
    </plurals>
</resources>

You can create a different file for different locales.

You can then access it in your code with:

final int months = Math.round(human_month);
return resources.getQuantityString(R.plurals.months, months, months)
PPartisan
  • 8,173
  • 4
  • 29
  • 48
  • using quantity strings is indeed better, while the `final` keyword is useless. – Martin Zeitler Mar 31 '19 at 11:18
  • @MartinZeitler More a question of coding style - I mark everything `final` unless it needs to be mutated – PPartisan Mar 31 '19 at 11:19
  • @MartinZeitler I still like it because it signifies intention - but you can leave it out, I'm not precious about it – PPartisan Mar 31 '19 at 11:21
  • in this case, it's a `final` local variable... where it's kind of verbosity overkill. there are situations, where the compiler produces less code, due to optimization - but on the other hand, the `GC` handles these differently. the values can still be mutated, it's only the reference to them that is `final`. – Martin Zeitler Mar 31 '19 at 11:42