using different string files in android

て烟熏妆下的殇ゞ 提交于 2019-12-05 07:02:38

Automatic locale selection, according to user settings

The strings.xml contains the original text, assuming for the English language. To create translations into different languages you can create folders, for example: values-gr, values.it, for the Greek end Italian. Just copy strings.xml into those folders and translate it.

On application launch, OS automatically picks a language according to the user's preferences.

Manually locale selection, overriding user settings

To force Greek for example you can use:

Locale locale = new Locale("gr"); 
            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

You should, of course, provide a Greek translation for this to work.

Read more

You can check the documentation here: Support Different Languages - Android

you have to put your localized strings in different folders like values-es, values-de, values-fr, etc.

The file must contain the same keys, for example in values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello</string>
</resources>

in values-es folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hola</string>
</resources>

and so on.

You have to create one values folder for each language adding the language ISO code of the language you want to have a translation using this format: values-es, values-de, ... In each folder you have to add a strings.xml with strings of its language. The values folder (withoud country code) will be the default language.

For choose the string language you want to use:

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;

public class Main extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String languageToLoad  = "fa"; // your language
    Locale locale = new Locale(languageToLoad); 
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config, 
    getBaseContext().getResources().getDisplayMetrics());
    this.setContentView(R.layout.main);
  }
}
Marek R

ad 1. No you can have as many as you want. See ad 3 for more information.

ad 2. ????

ad 3. To make language selection in our app you should update context. Then proper xml will be selected automatically. Read about this to see how to do it.

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