首页 > 解决方案 > 应用程序语言更改默认为原始语言

问题描述

我已经尝试在 API 27 上对此进行测试,并且效果很好,但是当我切换到 API 21 时,它不会改变语言。

private void setLocale(String lang) {

        Locale locale = new Locale(lang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();

  //config.locale = locale;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){

        config.setLocale(locale);

    } else {

        config.locale = locale;

    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){

        getBaseContext().createConfigurationContext(config);

    } else {

        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }

 //getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

    SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
    editor.putString("My_Lang", lang);
    editor.apply();

}


public void loadlocale(){

    SharedPreferences prefs = getSharedPreferences("Settings", Activity.MODE_PRIVATE);
    String language = prefs.getString("My_Lang", "");
    setLocale(language);
}

我在 onCreate 中的 setContentView 之前调用“loadlocal()”。

在我执行的 onClickListener 中

    ....
    setLocale("en");
    recreate();
//or
    setLocale("ar");
    recreate();
    ....

标签: javaandroidapiandroid-studiodeprecated

解决方案


推荐阅读