Search code examples
javaandroidandroid-studiolocale

Android: How to keep App Locale work independently from System Locale?


I have an issues related to display language. I am able to change the language inside the application ("en" for English and "ja" for Japanese) independently from OS system.

However, the problem is that when the application is in "ja" if users change the System language manually (not "en" or "ja") than my application auto-change the language to default ("en"). I want to make locale of my application stand alone, whatever language users change manually, the language of application still remain the same as when they log out.

EDIT

There are some useful links but they still cannot solve my problem. For example: Change language programatically in Android

Could you give my any suggestion to do it?

Thank you in advance!


Solution

  • Try this one:

    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; 
    
    public void setLocale(String lang) { 
        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();
    } 
    

    ADDED:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        newConfig.setLocale(yourLocale);
        super.onConfigurationChanged(newConfig);
    }
    

    ADDED(2):

    You have to set android:configChanges="layoutDirection|locale" in order to trigger onConfigurationChanged() when you change Locale.
    I cannot fully understand why this happens, maybe there are some RTL languages...