gpt4 book ai didi

android - 无法在 attachBaseContext() 中使用 Dagger 注入(inject)对象来更新语言环境

转载 作者:行者123 更新时间:2023-11-29 02:24:07 25 4
gpt4 key购买 nike

我正在使用 dagger,我必须在 activityattachBaseContext 中更新语言环境,我将语言环境更新逻辑保留在 LocaleManager 中,并且 LocaleManager 实例已经在里面appModule 当我尝试在 attachBaseContext 中使用此 LocaleManager 实例时,出现空指针异常因为 Activity 的注入(inject)发生在 onCreate() 内的 attachBaseContext 之后。

最佳答案

如您所说,这是因为注入(inject)是在调用 attachBaseContext 之后发生的。

其实我也不确定这里的问题是什么,但是我也遇到了同样的问题,可惜我没能用dagger解决。我需要像这样在 attachBaseContext 中创建一个新的 LocaleManager:

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

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

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);
}

关于android - 无法在 attachBaseContext() 中使用 Dagger 注入(inject)对象来更新语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com