简体   繁体   English

从共享首选项中读取语言环境设置不适用于MainActivity

[英]Reading locale settings from shared preferences doesn't work for the MainActivity

I am changing Locale settings inside my app with this method: 我正在使用以下方法在我的应用程序中更改区域设置:

public void setLanguageSettings(String localeLang){
    Locale locale = new Locale(localeLang);
    saveString("lang", localeLang);
    Locale.setDefault(locale);
    Configuration configSlo = new Configuration();
    configSlo.locale = locale;
    getBaseContext().getResources().updateConfiguration(configSlo, getBaseContext().getResources().getDisplayMetrics());
}

As you can see, the localeLang String variable is then saved to SharedPreferences. 如您所见,然后将localeLang String变量保存到SharedPreferences。 This variable is in my case either "sl" or "en" (default is "en" ). 在我的情况下,此变量为"sl""en" (默认为"en" )。

Then I'm calling this (same) method everytime the application starts (every time MainActivity is opened): 然后,每次应用程序启动时(每次打开MainActivity时)我都调用此(相同)方法:

String language = getString("lang");
setLanguageSettings(language);

The Locale is changed successfully (I checked with log) but the problem is that the change can't be seen in the MainActivity. 语言环境已成功更改(我检查了日志),但问题是在MainActivity中看不到更改。 If I open any other activity, the language is correct, but the MainActivity remains "en" even tho it is supposed to be "sl" . 如果我打开任何其他活动,则该语言是正确的,但是MainActivity仍然是"en"即使它应该是"sl" I'd have to restart MainActivity for it to be "sl" . 我必须重新启动MainActivity才能使其成为"sl"

I solved this question in a weird way. 我以一种奇怪的方式解决了这个问题。 I just called setContentView again in the change language method: 我只是在更改语言方法中再次调用setContentView:

setContentView(R.Layout.MainLayout);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM