Android 无法在attachBaseContext()中使用匕首注入对象来更新区域设置
我正在使用dagger,我必须更新Android 无法在attachBaseContext()中使用匕首注入对象来更新区域设置,android,android-7.0-nougat,dagger,Android,Android 7.0 Nougat,Dagger,我正在使用dagger,我必须更新活动的attachBaseContext中的区域设置,我将区域设置更新逻辑保留在LocaleManager中,并且当我尝试在attachBaseContext中使用此LocaleManager实例时,LocaleManager实例已经在appModule中,我得到空指针异常 由于活动的注入发生在attachBaseContext内部onCreate()之后,正如您所说,这是因为注入发生在调用attachBaseContext之后 实际上我不确定这里的问题是什么,
活动
的attachBaseContext
中的区域设置,我将区域设置更新逻辑保留在LocaleManager中,并且当我尝试在attachBaseContext中使用此LocaleManager实例时,LocaleManager实例已经在appModule中,我得到空指针异常
由于活动的注入发生在
attachBaseContext
内部onCreate()
之后,正如您所说,这是因为注入发生在调用attachBaseContext
之后
实际上我不确定这里的问题是什么,但我也面临着同样的问题,但不幸的是我无法用匕首解决它。我需要在attachBaseContext
中创建一个新的LocaleManager
,如下所示:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(new LocaleManager(base).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);
}
其中updateContext
返回具有更新区域设置的上下文,如下所示:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(new LocaleManager(base).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);
}