Home > Software design >  Changing the language of the android application doesn't work properly after selecting another
Changing the language of the android application doesn't work properly after selecting another

Time:01-27

My application that the user can change the language of the application. Currently, my application supports 5 languages. But when the user chooses another language, the language of the app will still be English.

Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.setLocale(new Locale(language_code.toLowerCase()));

Each time the application is launched, the selected language is set first. However, there is no change in the language! Of course, if i change the language before using Context.getString(R.string.name) every time, the selected language will be changed successfully!!.

CodePudding user response:

// Get the current locale
Locale currentLocale = getResources().getConfiguration().locale;

// Create a new configuration object
Configuration config = new Configuration();

// Set the new locale
config.locale = newLocale;

// Update the configuration
getResources().updateConfiguration(config, getResources().getDisplayMetrics());

You can replace newLocale with the desired locale, for example new Locale("es", "ES") for Spanish.

Additionally, you can also use the setLocale method of the Context class to change the locale.

Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = newLocale;
res.updateConfiguration(conf, dm);

You can also use the setDefault method of the Locale class to change the default locale for the entire app.

Locale.setDefault(newLocale);

Please note that you might need to call recreate() method after the configuration change. Also, you need to handle the case when the user changes the device language setting, and your app needs to reflect the changes.

CodePudding user response:

You must make these changes to the attachBaseContext function when you run each Activity.

public Context createConfiguration(Context context, String lan) {
    Locale locale = new Locale(lan);
    Configuration configuration = new Configuration(context.getResources().getConfiguration());
    configuration.setLocale(locale);
    return context.createConfigurationContext(configuration);
}

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(createConfiguration(newBase, "en"/*LANGUAGE_SELECTED*/)));
}

Alse for the activity you are in, after changing the language, call function recreate();.

  • Related