createConfigurationContext无法在API级别< 26上工作,无法以编程方式更改语言 [英] createConfigurationContext not working on API level <26 to change language programmatically

查看:102
本文介绍了createConfigurationContext无法在API级别< 26上工作,无法以编程方式更改语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关在运行时更改应用内语言的所有内容.目前,对于API 26 + 27 + 28 + 29而言,所有内容都可以正常运行(是的,我已经测试了所有这些内容),并且在API 25及以下版本开始崩溃.现在,我唯一知道API级别26中发生的事情是默认情况下,应用程序和活动不再共享相同的资源(也称为顶级资源).并且不赞成使用updateConfiguration for Resources来支持API 25中的createConfigurationContext

I've read everything about in-app language changing at runtime. Everything currently works correctly for API 26+27+28+29 (yes, I've tested all of them) and start breaking at API 25 and below. Now the only thing I know that happened in API level 26 was that application and activities no longer share the same resources (aka the top level resources) by default. And also that updateConfiguration for Resources gets deprecated in favor of createConfigurationContext in API 25

但这确实给了我零线索.

However that gives me zero clues really.

这是我的代码:

public class BaseApp extends MultiDexApplication { //for MinSDK < 21, otherwise "extends Application"

@Override
public void onCreate() {
    LocaleHelper.updateResources(this);
    super.onCreate();
}

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.updateResources(base));
    MultiDex.install(this); /* Needed as per (@link MultiDexApplication) */

}

@Override
public void onConfigurationChanged(Configuration config) {
    super.onConfigurationChanged(config);
    LocaleHelper.updateResources(this);
}

基本活动:

public abstract class BaseActivity extends AppCompatActivity {

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.updateResources(base));
}

Helper类:

class LocaleHelper {

static Context updateResources(Context context) {
    Resources resources = context.getResources();
    Configuration config = new Configuration(resources.getConfiguration());
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String lang = preferences.getString(Constants.PREF_KEY_LOCALE_OVERRIDE, Constants.PREF_VALUE_LOCALE_SYSTEM);
    Locale locale = new Locale(lang);

    if (Build.VERSION.SDK_INT >= 17) {
        config.setLocale(locale);
        context = context.createConfigurationContext(config);
    } else {
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }
    return context;
}

推荐答案

这是AndroidX的AppCompat实现中的已知错误.该错误位于1.0.0版中:"androidx.appcompat:appcompat:1.1.0"我确认它可以在该库的1.2.0版本中使用.

It is a kwown bug fo the AppCompat implementation of AndroidX. The bug is in the version 1.0.0: 'androidx.appcompat:appcompat:1.1.0' I confirm it works in the version 1.2.0 of the library.

这篇关于createConfigurationContext无法在API级别&lt; 26上工作,无法以编程方式更改语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆