javaandroidmultilingualdynamic-text

How can I make a multi-language app with the Java code?


I am already well aware of how easy it is to make a multilanguage app with Android by using the string.xml code. That part was nice and easy.

The issue is I have a lot of dynamic texts in my app that are made with my Java code. This is the part where I am can't find how to also make multilingual. The way I am picturing a solution is having some kind of condition in which I verify what language it is in, and change the string. For example:

 if(language.equals(English))
      textView1.setText("Hi! This is in English!");
 if(language.equals(Portuguese))
      textView1.setText("Oi! Isso é em Português!");

Is it possible for me to do something like this? If so, how can I do it?

Thanks!


Solution

  • Extract those strings into the strings.xml file too and it will choose the value from the correct file depending on the language. There is no reason to have those strings hardcoded in your java.

    String hello = getResources().getString(R.string.hello);
    

    Will have the right language if its available, since at runtime, the Android system uses the appropriate set of string resources based on the locale currently set for the user's device. For instance if you have res/values-ru/strings.xml that contains res/values/strings.xml and the device is in russian, it will take the value (if it's available) from the first one.