I have an activity where I programmatically set the locale to "de" and it doesn't work as expected and displays the default language (English text) that is manually set. Please help
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Programmatically sets the locale and language
Locale locale = new Locale("de");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show();
setContentView(R.layout.main);
Intent intent=new Intent(LatestLocalizationActivity.this,AnotherActivity.class);
startActivity(intent);
}
had you add the Strings.xml file in res->value-de folder?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Programmatically sets the locale and language
setContentView(R.layout.main);
config = getBaseContext().getResources().getConfiguration();
locale = new Locale("de");
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
refresh();
Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Configuration config = getBaseContext().getResources().getConfiguration();
// refresh your views here
Locale.setDefault(locale);
config.locale = locale;
super.onConfigurationChanged(newConfig);
}
private void refresh() {
finish();
Intent myIntent = new Intent(yourActivity.this, yourActivity.class);
startActivity(myIntent);
}
This worked for me:
public static void changeLocale(Context context, Locale locale) {
Configuration conf = context.getResources().getConfiguration();
conf.locale = locale;
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLayoutDirection(conf.locale);
}
context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
}
please use your ACTIVITY CONTEXT and not your application context.
Note that while you may be able to hack on things to kind-of get something like this to work, Android does not currently support doing this in a robust way. In particular, the framework works the current configuration in the resources, and will update it when it thinks appropriate. You will be fighting with this, and it is unlikely you are going to be able to have no situations where the configuration reverts back to the system locale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With