无法在attachBaseContext()中使用注入匕首的对象来更新语言环境 [英] Not able to use dagger-injected objects in attachBaseContext() to update locale

查看:277
本文介绍了无法在attachBaseContext()中使用注入匕首的对象来更新语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是匕首,我必须更新活动 attachBaseContext 中的语言环境,当我尝试在attachBaseContext中使用此LocaleManager实例时,LocaleManager和LocaleManager实例中的语言环境更新逻辑已位于appModule中,当活动注入发生在 attachBaseContext c>在 onCreate()中。

I am using dagger and I have to update the locale in the attachBaseContext of the activity, I am keeping the locale update logic inside LocaleManager and LocaleManager instance is already inside appModule when I try to use this LocaleManager instance inside attachBaseContext I get null pointer exception as the activity's injections happen after attachBaseContext inside onCreate().

推荐答案

您说过,因为注入是在调用 attachBaseContext 之后发生的。

This is happening, as you said, because the injection is happening after attachBaseContext is called.

我实际上不确定问题是什么在这里,但我面临着同样的问题,但不幸的是我无法用匕首解决。我需要在 attachBaseContext 中创建一个新的 LocaleManager ,像这样:

I'm actually not sure what the question is here, but I was facing the same problem, but unfortunately I could not solve it with dagger. I needed to create a new LocaleManager in the attachBaseContext like this:

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(new LocaleManager(base).updateContext());
}

其中 updateContext 返回具有更新后的语言环境的上下文,例如:

where updateContext returns the context with the updated locale, like this:

public Context updateContext() {
    Locale locale = new Locale(DESIRED_LANGUAGECODE);
    Locale.setDefault(locale);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResourcesLocale(locale);
    }
    return updateResourcesLocaleLegacy(locale);
}


@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Locale locale) {
    Resources resources = mContext.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return mContext;
}


@TargetApi(Build.VERSION_CODES.N)
private Context updateResourcesLocale(Locale locale) {
    Configuration configuration = mContext.getResources().getConfiguration();
    configuration.setLocale(locale);
    return mContext.createConfigurationContext(configuration);
}

这篇关于无法在attachBaseContext()中使用注入匕首的对象来更新语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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