在安卓5.0中更改应用程序语言无法生效。

7
我使用以下代码在按钮点击时更改应用程序语言(例如从法语更改为英语),它在Android 4.0+上运行良好,但在5.0上不起作用。
Locale localeEn = new Locale("en_US");
Locale.setDefault(localeEn);
Configuration configEn = new Configuration();
configEn.locale = localeEn;
getApplicationContext().getResources().updateConfiguration(configEn, null);
this.recreate();

有什么线索吗?
编辑: 这是我的清单(带有android:configChanges)
<activity
            android:name=".activities.LoginActivity"
            android:configChanges="orientation|locale"
            android:label="@string/app_name"
            android:screenOrientation="portrait"/>

你需要使用你的Activity context而不是Application context。 - Duda
1
这个回答解决了你的问题吗?在Android中以编程方式更改应用程序语言 - Heitor Paceli
最新的Android API 33中刚刚添加了每个应用程序语言功能,该版本仍处于开发者预览阶段。请参见我的答案:https://dev59.com/nHE85IYBdhLWcg3wMAfc#71151685 - Heitor Paceli
4个回答

13

尝试从这个方面进行改变:

Locale localeEn = new Locale("en_US");
Locale.setDefault(localeEn);

到这里

String language = "en";
String country = "US";
Locale locale = new Locale(language , country);

4

我从Udhay那里得到的解决方案,在用户在操作栏中更改语言并且应用程序使用所选语言进行“刷新”时有效。我正在使用Android 6.0。

无需将区域设置添加到androidManifest中。

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Locale locale = null;
    switch (item.getItemId()) {
        case R.id.action_en:
            locale = new Locale("en_US");
            Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_is:
            locale = new Locale("is", "IS");
                    Toast.makeText(this, "Íslanska", Toast.LENGTH_SHORT).show();
            break;

    }

    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = locale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, MainActivity.class);
    startActivity(refresh);
    finish();
    return true;
}

1

你在AndroidManifest.xml文件中是否添加了android:configChanges="locale"?我认为问题在于你的AndroidManifest.xml文件。

你可以在我的github存储库上查看更改语言环境的示例。


1
我的解决方案是在活动之前更改区域设置。
setContentView(R.layout.layout_main); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接