Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change app language in android 5.0 doesn't work

I'm using this code below to change my app language on button click (changing from french to english for example), it's works fine on android 4.0 + but on 5.0 it doesn't.

Locale localeEn = new Locale("en_US");
Locale.setDefault(localeEn);
Configuration configEn = new Configuration();
configEn.locale = localeEn;
getApplicationContext().getResources().updateConfiguration(configEn, null);
this.recreate();

Any clues why please?

edit : this is my manifest ( with android:configChanges )

<activity
            android:name=".activities.LoginActivity"
            android:configChanges="orientation|locale"
            android:label="@string/app_name"
            android:screenOrientation="portrait"/>
like image 355
Ahmed Abidi Avatar asked Aug 11 '15 15:08

Ahmed Abidi


2 Answers

Try to change from this:

Locale localeEn = new Locale("en_US");
Locale.setDefault(localeEn);

to this

String language = "en";
String country = "US";
Locale locale = new Locale(language , country);
like image 109
Jorge Casariego Avatar answered Sep 25 '22 02:09

Jorge Casariego


My solution, that i got from Udhay, works when user changes the language in actionbar and app "refreshes" with selected language. I am using android 6.0.

There is no need to add locale to androidManifest.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Locale locale = null;
    switch (item.getItemId()) {
        case R.id.action_en:
            locale = new Locale("en_US");
            Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_is:
            locale = new Locale("is", "IS");
                    Toast.makeText(this, "Íslanska", Toast.LENGTH_SHORT).show();
            break;

    }

    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = locale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, MainActivity.class);
    startActivity(refresh);
    finish();
    return true;
}
like image 25
Sindri Þór Avatar answered Sep 26 '22 02:09

Sindri Þór