I have a method that translates my application from English to Swedish and back again if the user so wishes. However, I don't really like the fact that the activity restarts every time because it's giving me a hard time with the savedInstaceState
and I've had several crashes because of this.
Here's how my method that changes language looks:
public void setApplicationLanguage(String language) {
myLocale = new Locale(language);
Resources res = activity.getResources();
DisplayMetrics display = res.getDisplayMetrics();
Configuration configuration = res.getConfiguration();
configuration.locale = myLocale;
res.updateConfiguration(configuration, display);
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
}
Is there any chance that the same function can be applied without the:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
?
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);
onConfigurationChanged(conf);
/*Intent refresh = new Intent(this, AndroidLocalize.class);
startActivity(refresh);*/
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
lblLang.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
android:configChanges="locale"
You can replace the code:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
With the method from Activity class:
recreate();
I hope your minimum SDK version will support because it was introduce in SDK 11. Your activity will be recreate as a new instance remember! Everything will be started afresh. From my experience it is fast compared to making a new Intent
. But if you want to pass some data the method of using Intent
is better than that! You can add extras to the 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