第一步,需要在build.gradle中配置Hilt的插件路径:
buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
}
第二步,在app/build.gradle中添加Hilt依赖库与引入插件
plugins{
id:'kotlin-kapt',
id:'dagger.hilt.android.plugin'
}
...
dependencies {
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
}
必须自定义Application,否则Hilt将无法正常工作 ```kotlin @HiltAndroidApp class MyApplication : Application() { }
```kotlin
<application
android:name=".MyApplication"
...>
</application>
- Hilt一共支持6个入口点,分别是
- Application
- Activity
- Fragment
- View
- Service
- BroadcastReceiver
- Hilt中的InstallIn支持7中组件类型
- @ApplicationComponent:Application
- @ActivityRetainedComponent:ViewModel
- @ActivityComponent:Activity
- @FragmentComponent:Fragment
- @ViewComponent:View
- @ViewWithFragmentComponent:View annotated with @WithFragmentBindings
- @ServiceComponent:@Service
只有Application这个入口点是使用@HiltAndroidApp注解来声明的,其余全部都是@AndroidEntryPoint