Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change language without restarting activity

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);

?

like image 852
Jens O. Anders Olsén Avatar asked Oct 31 '17 12:10

Jens O. Anders Olsén


2 Answers

Try this

  • I also had this issue.I used the code below and then it changed the language without refreshing the activity

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();
}
  }

  • declare in Manifest android:configChanges="locale"
like image 129
Vishal Yadav Avatar answered Oct 31 '22 04:10

Vishal Yadav


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.

like image 39
Xenolion Avatar answered Oct 31 '22 04:10

Xenolion