如何为HiltAndroid提供上下文?
我正在尝试将项目迁移到 Hilt,但面临以下问题,不确定如何使用 Hilt 传递上下文。如果我删除provideContext方法,那么它会抱怨以下错误:
error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ApplicationContext android.content.Context cannot be provided without an @Provides-annotated method.
但我的理解是,在 Hilt 中我们不需要provideContext方法,我们可以@ApplicationContext像下面这样使用:
@Inject
public CardLayoutManager(@ApplicationContext Context context) {
mContext = context;
}
我错过了什么吗?
回答
您需要正确注释构造函数:
class CardLayoutManager @Inject constructor(@ApplicationContext val context: Context) {
}