首页 > 解决方案 > 如何为 Hilt Android 提供上下文?

问题描述

我正在尝试将项目迁移到 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;
}

我错过了什么吗?

标签: androidkotlindependency-injectiondaggerdagger-hilt

解决方案


您需要正确注释构造函数:

class CardLayoutManager @Inject constructor(@ApplicationContext val context: Context) {
}

推荐阅读