以编程方式更改应用程序语言并使用 SharedPreferences 维护语言

programmatically changing app language and maintain language with SharedPreferences

我试图在导航抽屉列表中单击语言名称时以编程方式更改应用程序语言。语言发生变化,但当应用程序关闭时我无法维护。 这是我的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);
    }

您应该将具有新配置的上下文传递给您的 activity

使用这个 LocaleHelper(用 Kotlin 编写,但您也可以在 Java 中自己完成)

然后在你的activity中调用这个方法

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)
}

我正在使用 在运行时更改应用程序语言。

and I call this method in onCreate to get the stored language, but it doesn't work.

如果语言设置完成,我的解决方案就可以工作 (loadLocale()) super.OnCreate() 被调用之前

@Override
protected void onCreate(Bundle savedInstanceState) {
    loadLocale();
    super.onCreate(savedInstanceState);
    ... initialize
}