当在导航抽屉列表中单击语言名称时,我试图以编程方式更改应用程序语言。语言变化,但我无法维持当应用程序关闭。这里是我的setLocal
方法
private void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE).edit();
editor.putString(MY_LANG,lang);
editor.apply();
}
当我想要像这样改变朗的时候,我调用这个方法
if (id == R.id.ar_lang){
setLocale("ar");
recreate();
}
if (id == R.id.eng_lang){
setLocale("en");
recreate();
}
我在onCreate中调用这个方法来获取存储的语言,但是它不起作用。
public void loadLocale(){
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
String languages = prefs.getString(MY_LANG,"");
setLocale(languages);
}
发布于 2020-06-14 02:17:36
我正在使用https://stackoverflow.com/a/34675427/519334在运行时更改应用程序语言。
我在onCreate中调用这个方法来获取存储的语言,但是它不起作用。
如果在调用loadLocale()
super.OnCreate()之前已经完成了(super.OnCreate()super.OnCreate),那么我的解决方案会工作。
@Override
protected void onCreate(Bundle savedInstanceState) {
loadLocale();
super.onCreate(savedInstanceState);
... initialize
}
发布于 2020-06-14 01:40:34
您应该将新配置的上下文传递给您的活动。
使用这个LocaleHelper (用Kotlin编写,但也是用Java自己编写的)
然后在您的活动中调用此方法
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(LocaleHelper.onAttach(newBase!!))
}
override fun applyOverrideConfiguration(overrideConfiguration: Configuration?)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
// update overrideConfiguration with your locale
overrideConfiguration?.setLocale(LocaleHelper.getCurrentLocale(this))
overrideConfiguration?.setLayoutDirection(LocaleHelper.getCurrentLocale(this))
}
super.applyOverrideConfiguration(overrideConfiguration)
}
https://stackoverflow.com/questions/62370649
复制相似问题