Android 当应用程序关闭并再次打开时,如何加载已更改的语言
我正在尝试更改我的应用程序的语言。所以,我尝试了下面的代码,它工作得很好Android 当应用程序关闭并再次打开时,如何加载已更改的语言,android,Android,我正在尝试更改我的应用程序的语言。所以,我尝试了下面的代码,它工作得很好 Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { conf.setLocale(ne
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(new Locale(localeCode.toLowerCase()));
} else {
conf.locale = new Locale(localeCode.toLowerCase());
}
res.updateConfiguration(conf, dm);
SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
editor.putString("My_Lang", localeCode);
editor.apply();
Intent refresh = new Intent(this, StartupActivity.class);
startActivity(refresh);
finish();
现在,当我关闭应用程序并再次打开时,语言设置为默认英语。我不知道如何通过共享首选项加载语言资源。请帮助我保留更改的语言,即使应用程序已被删除 使用以下语句从SharedReferences读取数据
SharedPreferences pref=getSharedPreferences("Settings", MODE_PRIVATE);
String value=pref.getString("My_Lang","");
上述值中的数据存储在共享首选项中
下面给出的更新代码:尝试下面的代码(这是上面@Harsha给出的答案的更新,请参考该答案并更新我的代码)
记住活动状态;在活动的
OnCreate
方法中检索SharedReferences
值(如果存在),并确保在调用setContentView
之前调用updateConfiguration
方法
另外,如果需要确保在重新启动活动之前本地保存此首选项,请尝试调用editor.commit()
方法,而不是editor.apply()
如果您可以在后台线程中存储首选项,请使用editor.apply()
方法
编辑:以下是您在代码中的错误。
您正在重新启动活动之前更新资源
您应该做的是在调用setContentView之前检索语言首选项并加载资源
因此,当您保存语言首选项时
SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
editor.putString("My_Lang", localeCode);
editor.apply();
Intent refresh = new Intent(this, StartupActivity.class);
startActivity(refresh);
finish();
当您在重新启动的活动中加载新语言时
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(new Locale(localeCode.toLowerCase()));
} else {
conf.locale = new Locale(localeCode.toLowerCase());
}
res.updateConfiguration(conf, dm);
//and then
setContentView(layoutId)
我试过了,但没有日志。告诉我如何处理这个值。@vikas Acharya:我被添加了一些分数。请参考我更新的答案
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(new Locale(localeCode.toLowerCase()));
} else {
conf.locale = new Locale(localeCode.toLowerCase());
}
res.updateConfiguration(conf, dm);
//and then
setContentView(layoutId)