124

I want my app to support three languages Spanish,Portuguese & English. And give option to select language in app.I have made

1) 3 drawable folders drawable-es,drawable-pt,drawable.

2) 3 values folder values-es,values-pt,values.Change String.xml values according to languages.

I have imageView to select language.When click it menu open that consists option English,Spanish,Portuguese.

I set Locale inside app on option selection by this code

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.en:
             Locale locale = new Locale("en"); 
             Locale.setDefault(locale);
             Configuration config = new Configuration();
             config.locale = locale;
             getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
             Toast.makeText(this, "Locale in English !", Toast.LENGTH_LONG).show();
             break;

        case R.id.pt:
             Locale locale2 = new Locale("pt"); 
             Locale.setDefault(locale2);
             Configuration config2 = new Configuration();
             config2.locale = locale2;
             getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics());

             Toast.makeText(this, "Locale in Portugal !", Toast.LENGTH_LONG).show();
             break;

        case R.id.es:
             Locale locale3 = new Locale("es"); 
             Locale.setDefault(locale3);
             Configuration config3 = new Configuration();
             config3.locale = locale3;
             getBaseContext().getResources().updateConfiguration(config3, getBaseContext().getResources().getDisplayMetrics());

             Toast.makeText(this, "Locale in Spain !", Toast.LENGTH_LONG).show();
             break;     
    }
    return super.onOptionsItemSelected(item);
}

I have declare in Manifest- android:configChanges="locale"

It work but it have some issue.

Problem:-

1)When language selected, screen that consists image of language selection not change but other screens are change.

2)After orientation change app restore language according to locale of phone.

Uma Sankar
  • 449
  • 1
  • 8
  • 19
mukesh
  • 4,140
  • 5
  • 29
  • 40
  • 1
    For the 2nd problem try adding: `android:configChanges="locale"` for your Activity inside the AndroidManifest.xml – Parth Doshi Oct 16 '12 at 06:13
  • i have already add in every activitiy in my manifest. – mukesh Oct 16 '12 at 06:14
  • You can use the following library, which provides the language list, the preference for your settings screen, and overrides the language in your application: https://github.com/delight-im/Android-Languages – caw Aug 30 '14 at 16:07

9 Answers9

188

It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/

It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.

public void setLocale(String lang) { 
    Locale myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, AndroidLocalize.class); 
    finish();
    startActivity(refresh); 
} 

Make sure you imported following packages:

import java.util.Locale; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.content.res.Resources; 
import android.util.DisplayMetrics; 

add in manifest to activity android:configChanges="locale|orientation"

Community
  • 1
  • 1
Udhay
  • 1,946
  • 1
  • 12
  • 6
  • 2
    Yeah sure. I can provide the excerpt of the web page. Where I need to provide please let me know. Thanks. – Udhay Oct 18 '12 at 12:08
  • As an additional information for you, my AVD became error. So I deleted `Intent refresh = new Intent(this, AndroidLocalize.class); startActivity(refresh);` and placed it in `onSharedPreferenceChange` method. Simply, I placed it out of `setLocale(String lang)` subclass. And it worked now. – Anggrayudi H Dec 08 '14 at 14:59
  • How to add polish in language translation, as the local.class dosnt have the polish entry in it. How to do that? – BalajiG Feb 24 '15 at 06:33
  • 4
    Be sure to add finish() so that you don't have two copies of your activity in the navigation stack. – Joel Teply Jun 08 '15 at 22:03
  • 7
    `finish()` needs to be called before `startActivity(refresh)`. Otherwise App may exit instead of the Activity being restarted. – Mohammed Ali Oct 25 '15 at 15:20
  • 11
    Hi, I did it, it works, but when I restart the app, it returns to the default language .. – Sofiane Hassaini Apr 21 '16 at 12:01
  • Yeah, It's working fine but I'm facing one issue in this code. Suppose I change my app language English to arabic using this code.It's working fine but Once I kill application then restart this app my application language will be automatically reset.I active with english language.Is it possible to my application language remain same which user previously selected without using Shared Preferance? – Chirag Solanki Apr 11 '17 at 06:11
  • 7
    Configuration config = new Configuration(newConfig); config.locale = locale; In my case getting this message. locale deprecated in API level 25 – Milon May 11 '17 at 10:08
  • 5
    This answer needs to be updated since some of the APIs used are now deprecated. – Sajib Acharya Sep 22 '18 at 11:08
  • @Udhay If we have change the app language then if we have some searching option within app, and if we search in that then, how app will show data, should we develop some different database for each language or some android code setting is there so that app could show data according to search ? – Vishwa Pratap Sep 16 '19 at 08:35
  • 1
    In case you set a RTL locale like Arabic "ar" and want your -ldrtl resource folders to work as well then also call conf.setLayoutDirection(locale); under conf.locale = myLocale; – Aziz Nov 04 '20 at 12:47
  • Instead of `finish` and `startActivity` , you can simply use `activity.recreate()` – beginner Mar 10 '22 at 11:13
12

all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)

public void setLocale(String lang) { 
    Locale myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, AndroidLocalize.class); 
    finish();
    startActivity(refresh); 
} 

Mine was not working just because the languages were not mentioned in the config file(build.gradle)

 defaultConfig {
    resConfigs "en", "hi", "kn"
}

after that, all languages started running

Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40
Lokesh Tiwari
  • 10,496
  • 3
  • 36
  • 45
11

Good solutions explained pretty well here. But Here is one more.

Create your own CustomContextWrapper class extending ContextWrapper and use it to change Locale setting for the complete application. Here is a GIST with usage.

And then call the CustomContextWrapper with saved locale identifier e.g. 'hi' for Hindi language in activity lifecycle method attachBaseContext. Usage here:

@Override
protected void attachBaseContext(Context newBase) {
    // fetch from shared preference also save the same when applying. Default here is en = English
    String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
    super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}
sud007
  • 5,824
  • 4
  • 56
  • 63
  • Thanks for the link it is working but i didn't understand a few things , i just called the `MyContextWrapper.warp` in `onAttach` of just one fragment of my app but the language was changed for the whole app, but the activity titles were not changed , i think it is because the manifest titles takes precedence , but if i call the same method in `onAttachBaseContex` on my subclass of application the activity titles also changes to selected language , but then the changes are only applied to the fragment i called in the warp method, why is that ? – Abhinav Chauhan May 02 '20 at 04:04
  • @AbhinavChauhan I am not sure about this to be true. I need to check that one. I have never faced this issue when I implemented this solution. However, It has been long time and there may be some changes in the Android implementation for newer versions. Alternatively try some newest answers on this post. – sud007 May 03 '20 at 10:42
  • i tried many solution but non of them worked or maybe i implemented them incorrectly , may your class works good with activities , i am using it `warp` method in `onAttach` of the fragment ,previously i said i just needed to do it with mainactivity fragment and language changed in whole app it is true, but for all other fragments language changes to english on configuration change so i need to put in `onattach` of all the fragments and instead of manifest i set the actionbar titles in code , now the app is working as expected. thanks – Abhinav Chauhan May 03 '20 at 10:51
  • Okay! I am sure you do not have to do this for every screen, just the first activity that launches and inside the `attachBaseContext` function only. And that does it for all the screens. Have you created a `BaseActivity' for all activities in your app? – sud007 May 03 '20 at 17:42
  • No i was trying to do it in the my subclass of application thinking that it will be applied to whole application , then in all fragments, but it turns out that the `wrap()` code needs to be executed at every configuration changes , so i putted it in the Abstract activity from which all other activities extends , now it is working – Abhinav Chauhan May 06 '20 at 12:30
6

You should either remove android:configChanges="locale" from manifest, which will cause activity to reload, or override onConfigurationChanged method:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
    // your code here, you can use newConfig.locale if you need to check the language
    // or just re-set all the labels to desired string resource
}
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Frane Poljak
  • 2,315
  • 23
  • 25
  • 1
    Removing android:configChanges="locale" from manifest does not prevent app from restarting. It will restart regardless of if that is added to manifest or not. – portfoliobuilder Sep 20 '18 at 01:01
  • I'm not saying that removing android:configChanges="locale" from manifest prevents the app from restarting, I'm saying exactly the opposite. Now, for the case when we have android:configChanges="locale" in the manifest, it used to prevent the app from reloading at the time I wrote this answer, I can't say for sure it's the case now. – Frane Poljak Sep 20 '18 at 08:49
5

Kotlin solution using context extension

fun Context.applyNewLocale(locale: Locale): Context {
    val config = this.resources.configuration
    val sysLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.locales.get(0)
    } else {
        //Legacy
        config.locale
    }
    if (sysLocale.language != locale.language) {
        Locale.setDefault(locale)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale)
        } else {
            //Legacy
            config.locale = locale
        }
        resources.updateConfiguration(config, resources.displayMetrics)
    }
    return this
}

Usage

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(newBase?.applyNewLocale(Locale("es", "MX")))
}
3

Udhay's sample code works well. Except the question of Sofiane Hassaini and Chirag SolankI, for the re-entrance, it doesn't work. I try to call Udhay's code without restart the activity in onCreate() , before super.onCreate(savedInstanceState);. Then it is OK! Only a little problem, the menu strings still not changed to the set Locale.

    public void setLocale(String lang) { //call this in onCreate()
      Locale myLocale = new Locale(lang); 
      Resources res = getResources(); 
      DisplayMetrics dm = res.getDisplayMetrics(); 
      Configuration conf = res.getConfiguration(); 
      conf.locale = myLocale; 
      res.updateConfiguration(conf, dm); 
      //Intent refresh = new Intent(this, AndroidLocalize.class); 
      //startActivity(refresh); 
      //finish();
    } 
Fisher
  • 488
  • 7
  • 24
  • same problem with menu strings. Do you solve the problem? – AlexS Dec 30 '18 at 21:14
  • @AlexS, I didn't find ways to fix the problem in menu string. But found to exit the app and then reenter , the menu strings can be normally changed to the new Locale. – Fisher Jan 02 '19 at 13:50
  • you mean `Intent refresh = new Intent(this, ThisActivity.class); startActivity(refresh); `? – AlexS Jan 02 '19 at 14:31
  • 2
    @AlexS, No! adding the new Intent() and startActivity() may make it return to the default language when restart the app. What I mean is if users exit the app and reenter the app, the menu strings can be changed to the new Locale. – Fisher Jan 03 '19 at 06:28
3

Those who getting the version issue try this code ..

public static void switchLocal(Context context, String lcode, Activity activity) {
        if (lcode.equalsIgnoreCase(""))
            return;
        Resources resources = context.getResources();
        Locale locale = new Locale(lcode);
        Locale.setDefault(locale);
        android.content.res.Configuration config = new 
        android.content.res.Configuration();
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
        //restart base activity 
        activity.finish();
        activity.startActivity(activity.getIntent());
    }
Pierre-Loup Pagniez
  • 3,611
  • 3
  • 29
  • 29
Wahab Khan Jadon
  • 875
  • 13
  • 21
2

There's a new (and better) implementation for in-app language pickers since Appcompat 1.6.0-alpha04 and later: https://developer.android.com/about/versions/13/features/app-languages#androidx-impl

Methods used in custom implementations suggested by others are deprecated in API level 25.

0
    Locale locale = new Locale(langCode);
    Locale.setDefault(locale);
    Configuration configuration = context.getResources().getConfiguration();
    configuration.locale = locale;
    configuration.setLayoutDirection(locale); // for RTL changes
    preferences.setLocalePref(langCode);
    context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());

Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState) in onCreate.

Mrudul Tora
  • 715
  • 8
  • 14