I have build an application in Android Studio (using only java not kotlin). Recently I started to create translations to make it multilingual and I need to use a function to change the app language.
I have a function to change the locale of my application in my MainActivity and it works, problem is I can't use it MainActivity because I want to use it in my settings activity, but I also want to define the local based on the one that user saved last time and not the android system one. I've placed the function in my "MyApplication class" (extends Application) and I'm doing MyApplication.getInstance().setLocale("en"). But it ignores and goes into the mobile system language.
This is the function that works in the MainActivity but not in the MyApplication class
public void setLocale(String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Configuration configuration = getResources().getConfiguration();
configuration.setLocale(locale);
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
}
If I set the function in MainActivity class i use this line in the "OnCreate" of MainActivity:
setLocale("en");
Works. But I need it in another class so, MyApplication, and I set this line in the "OnCreate" of MainActivity:
MyApplication.getInstance().setLocale("en");
This don't work, exact code but different places I've tried debug and it's going where it should go, but doesn't change the language.
Put your code of setLocale inside method (of Activity):
@Override
protected void attachBaseContext(Context newBase) {...}
You need create a abstract/open BaseActivity class, and set Locale for it, and then any activity extended from BaseActivity will be apply Locale.