问题看起来是这样的。在我的应用程序中,我有 3 个活动(到目前为止,第四个即将到来)。其中之一是设置屏幕,用户可以在其中选择他的语言。当设置更改时,我会更新活动,现在魔法来了……所有活动都会改变它们的语言,除了一个 - 主菜单活动。无论我做什么,它都适用于除此之外的所有活动。有趣的是,我已经检查并完成了更新本地人的方法,并且还使用了正确的语言设置。
主要活动代码(我已经删除了在这种情况下无关紧要的代码):
public class MainMenuActivity extends AppCompatActivity {
private Preferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
initialize();
}
@Override
public void onResume() {
applySettings();
super.onResume();
}
private void initialize() {
preferences = Preferences.getInstance();
preferences.initiate(this);
}
private void applySettings() {
Toast.makeText(this, getResources().getConfiguration().locale.getDisplayName(), Toast.LENGTH_LONG).show();
Activity.setLocale(getApplicationContext(), preferences.getLanguage().getValue());
}
}
这是设置本地人的方法:
public class ActivitySettings {
public static void setLocale(Context context, String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration conf = new Configuration();
conf.locale = locale;
Resources res = context.getResources();
res.updateConfiguration(conf, res.getDisplayMetrics());
}
如您所见,我在更新之前添加了显示当前语言的行,它表明语言是正确的。为什么它不会改变主要活动的语言?!
编辑 - 找到了解决方案
我在主要活动中添加了新变量
private Locale currentLocal = null;
然后在启动时我将其设置为当前语言环境
currentLocal = Locale.getDefault();
现在在 onResume() 我已经添加了
if (currentLocal.getLanguage() != Locale.getDefault().getLanguage()) {
currentLocal = Locale.getDefault();
recreate();
}
现在它完美无缺。