语言环境不会在活动之间保存

问题描述

我创建了一个可以同时使用希伯来语和英语的应用程序。

在我的应用程序的“设置”部分中,有一个按钮用于说出更改语言。

用户单击它时,它会执行以下操作:

SharedPreferences lang_settings = getSharedPreferences( AppConstants.PREFS_NAME,MODE_PRIVATE );
Lang = lang_settings.getString( AppConstants.PREF_LANG,"en" );
btn_Language.setonClickListener( v -> {
    if (Lang.equals( "iw" )) {
        popUps.changeLanguage( this,"en");
        updatedLang = "en";
    } else {
        popUps.changeLanguage( this,"iw");
        updatedLang = "iw";
    }
    SharedPreferences.Editor editor = getSharedPreferences( AppConstants.PREFS_NAME,MODE_PRIVATE ).edit();
    editor.putString( AppConstants.PREF_LANG,updatedLang );
    editor.apply();
} );

哪里

public void changeLanguage(Context context,String Language){
    Locale myLocale = new Locale(Language);
    Resources res = context.getResources();
    displayMetrics dm = res.getdisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    conf.setLayoutDirection(myLocale);
    res.updateConfiguration(conf,dm);
    Intent refresh = new Intent(context,SettingsActivity.class);
    if(context instanceof Activity){
        ((Activity)context).finish();
    }
    context.startActivity(refresh);
}

现在,到目前为止一切顺利。我真的改变了语言,一切都很好。

但是,假设用户在应用程序中选择了希伯来语作为首选语言,但设备的认语言是英语。当用户启动应用程序时,我想检查一下以前在SharedPreferences中保存的内容并加载了该语言。因此,我尝试在主要活动中使用以下代码

SharedPreferences lang_settings = getSharedPreferences( AppConstants.PREFS_NAME,"en" );
if (Lang.equals( "iw" )) {
    changeLanguage( "en" );
} else {
    changeLanguage( "iw" );
}

private void changeLanguage(String Language) {
    Locale myLocale = new Locale( Language );
    Resources res = getResources();
    displayMetrics dm = res.getdisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    conf.setLayoutDirection( myLocale );
    res.updateConfiguration( conf,dm );
}

但是我遇到2个问题:

  1. 该应用更改了语言,但是某些图标没有像以前一样移至rtl

  2. 该应用仅针对下一个活动更改了其语言,如果我随后转到另一个活动,它将返回认的设备语言。

关于如何使应用程序始终使用SharedPreferences显示的首选语言的任何想法?我需要检查它在每个活动中存储什么吗?

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)