Android Localization with resources in Android Adding translation to your Android app

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You have to create a different strings.xml file for every new language.

  1. Right-click on the res folder
  2. Choose NewValues resource file
  3. Select a locale from the available qualifiers
  4. Click on the Next button (>>)
  5. Select a language
  6. Name the file strings.xml

strings.xml

<resources>
    <string name="app_name">Testing Application</string>
    <string name="hello">Hello World</string>
</resources>

strings.xml(hi)

<resources>
    <string name="app_name">परीक्षण आवेदन</string>
    <string name="hello">नमस्ते दुनिया</string>
</resources>

Setting the language programmatically:

public void setLocale(String locale) // Pass "en","hi", etc.
{
    myLocale = new Locale(locale);
    // Saving selected locale to session - SharedPreferences.
    saveLocale(locale);
    // Changing locale.
    Locale.setDefault(myLocale);
    android.content.res.Configuration config = new android.content.res.Configuration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocale(myLocale);
    } else {
        config.locale = myLocale;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        getBaseContext().createConfigurationContext(config);
    } else {
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
}

The function above will change the text fields which are referenced from strings.xml. For example, assume that you have the following two text views:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/app_name"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

Then, after changing the locale, the language strings having the ids app_name and hello will be changed accordingly.



Got any Android Question?