I want to programmatically change the language.
So I have built two xml files.
values-it
-->string.xml
values-en
-->string.xml
This is the code in MainActivity to change the language of the whole application:
//ITALIAN
Resources res = getApplicationContext().getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("it");
res.updateConfiguration(conf, dm);
//ENGLISH
Resources res2 = getApplicationContext().getResources();
DisplayMetrics dm2 = res2.getDisplayMetrics();
android.content.res.Configuration conf2 = res2.getConfiguration();
conf2.locale = new Locale("en");
res2.updateConfiguration(conf2, dm2);
Now if I set the English language (for example) the code is executed with no error, but the label doesn't not change its text.
If I change the orientation of my device, the label changes its text correctly.
Now how can I modify my code to automatically refresh the label?
AlertDialog.Builder builder = new AlertDialog.Builder(DashboardActivity.this);
builder.setTitle(R.string.languages);
// Add the buttons
builder.setPositiveButton(R.string.english, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
dialog.dismiss();
rEditor.putString("language", languageToLoad);
rEditor.commit();
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
}
});
builder.setNegativeButton(R.string.gujarati, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
String languageToLoad = "gu"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
dialog.dismiss();
rEditor.putString("language", languageToLoad);
rEditor.commit();
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
}
});
builder.create().show();
you have to reload activity to show new language text means restart.
you need to refresh your activity to load resources which it does incase of changing the orientation. try this
private void restartActivity() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
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