简体   繁体   中英

Translating String values that are in a Java File in Android Studios

I'm making a simple app for fun to show random facts every time a button is pressed. I'm looking into making translations for my app, but I am not sure how to translate these sentences. My facts are all located in a Java Class.

Here is my Facts Java class:

String facts[] = { 
            "In some cultures' telling of Snow White, the dwarves are thieves.",
            "Sea otters hold each other's paws while sleeping so they don't drift apart.",
            "The longest attack of hiccups ever lasted 68 years.", };

I've never translated sentences that came from a Java Class before, so I don't understand how to do this. Am I supposed to copy these values and put them in the strings.xml folder, or am I not on the right track?

Yes, you should place them in an xml file.

You can use a StringArray

You can load them from the resources.

String[] facts = getContext().getResources().getStringArray(R.arrays.random_facts);

You can localize the string resources to get different translations.

You should use a ResourceBundle .

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows you to write programs that can:

  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locales

Eg use a PropertyResourceBundle and put the text in a set of property files, one file per language.

Facts_en.properties :

f1=In some cultures' telling of Snow White, the dwarves are thieves.
f2=Sea otters hold each other's paws while sleeping so they don't drift apart.
f3=The longest attack of hiccups ever lasted 68 years.

Facts_da.properties :

f1=I nogle kulturers fortællinger om Snehvide, er dværgene tyve.
f2=Havoddere holder hinandens poter, mens de sover, så de ikke glider fra hinanden.
f3=Den længste angreb af hikke nogensinde varede 68 år.

You then call getBundle() to get the facts:

ResourceBundle bundle = ResourceBundle.getBundle("Facts", Locale.ENGLISH);
String fact1 = bundle.getString("f1");

Read The Java™ Tutorials - Lesson: Isolating Locale-Specific Data to learn more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM