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

问题描述 投票:0回答:2

我正在尝试在导航抽屉列表中单击语言名称时以编程方式更改应用程序的语言。语言已更改,但关闭应用程序后无法维护。这是我的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);
    }
java android sharedpreferences
2个回答
0
投票

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

使用此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)
}

0
投票

我正在使用https://stackoverflow.com/a/34675427/519334在运行时更改应用语言。

并且我在onCreate中调用此方法来获取存储的语言,但是它不起作用。

如果完成语言设置(loadLocale()),[我的解决方案仅适用于之前 super.OnCreate()被调用]

@Override
protected void onCreate(Bundle savedInstanceState) {
    loadLocale();
    super.onCreate(savedInstanceState);
    ... initialize
}
© www.soinside.com 2019 - 2024. All rights reserved.