我发现@AndroidEntryPoint 注释需要在视图、片段(如果在片段中)和活动上。因为注解。
因此,假设您的 DI 设置如下:
/* CONTENTS OF com.org.app.di/dependencyModule.kt */
@Module
@InstallIn(ViewComponent::class)
object DependencyModule {
@Provides
fun provideDependency(@ApplicationContext context: Context): DependencyType
= DependencyInstance(context)
}
我的应用程序设置正确:
@HiltAndroidApp
class SuperAwesomeApplication : Application()
/* Remember to reference this is the manifest file, under the name attricbute! */
现在,如果我有一个带有注入依赖项的视图:
@AndroidEntryPoint
class SuperAwesomeView(context: Context, attrs: AttributeSet) : View(context, attrs) {
@Inject
lateinit var dependency: DependencyType
...
我会得到错误:
...
Caused by: java.lang.IllegalStateException: class com.app.org.ui.view.SuperAwesomeView, Hilt view must be attached to an @AndroidEntryPoint Fragment or Activity.
...
所以我将@AndroidEntryPoint注解添加到包含视图的Fragment中:
@AndroidEntryPoint
class SuperAwesomeFragment : Fragment() {
...
然后我们遇到下一个错误:
Caused by: java.lang.IllegalStateException: Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class com.org.ui.SuperAwesomeActivity
所以我了解到注释需要一直冒泡,从 View 到(如果在 Fragment 中)Fragment,再到 Activity:
@AndroidEntryPoint
class SuperAwesomeActivity : AppCompatActivity() {
...