I am having a trouble with changing app language programmatically on android versions under api.23 (currently testing on device with android 5) I have no idea what to do, so here is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
PreferenceRepository preferenceRepository;
@SuppressLint({"NonConstantResourceId", "SourceLockedOrientationActivity"})
@Override
protected void onCreate(Bundle savedInstanceState) {
preferenceRepository = new PreferenceRepository(this);
//Sets selected by user language on start
setLocale(preferenceRepository.loadLocale());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialization
RadioButton GeLang = findViewById(R.id.GeorgianLang);
RadioButton EnLang = findViewById(R.id.EnglishLang);
RadioGroup LanguageApp = findViewById(R.id.Language);
//Checks Radio button according to app language
if (Locale.getDefault().getDisplayLanguage().equals("ქართული")){
GeLang.setChecked(true);
} else {
EnLang.setChecked(true);
}
//Changes language according to checked button
LanguageApp.setOnCheckedChangeListener((LanguageApp1, i) -> {
switch (i) {
case R.id.GeorgianLang:
setLocale("ka");
recreate();
break;
case R.id.EnglishLang:
setLocale("en");
recreate();
break;
}
});
}
//Updates configuration and loads the checked language
private void setLocale(String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
preferenceRepository.setLocale(language);
}
}
**PreferenceReposytory.class:**
public class PreferenceRepository {
SharedPreferences mySharedPref ;
public PreferenceRepository(Context context) {
mySharedPref = context.getSharedPreferences("filename",Context.MODE_PRIVATE);
}
//Loads language when app starts
public String loadLocale() {
return mySharedPref.getString("My_Language", "");
}
//Saves state when language is changed
public void setLocale(String language){
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putString("My_Language", language);
editor.apply();
}
}
I'd like to thank you in advance for your assistance and I'm looking forward to hearing from you soon.