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.

2

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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)

4 Comments

using quantity strings is indeed better, while the final keyword is useless.
@MartinZeitler More a question of coding style - I mark everything final unless it needs to be mutated
@MartinZeitler I still like it because it signifies intention - but you can leave it out, I'm not precious about it
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.