GradlePluginを追加
build.gradle
buildscript {
ext.hilt_version = '2.28-alpha'
repositories {
...
google()
}
dependencies {
...
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
}
}
Dependencyを追加
app/build.gradle
...
apply plugin: 'dagger.hilt.android.plugin'
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
...
kapt "com.google.dagger:dagger-compiler:$versions.dagger2"
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
}
Annotationを追加
App.kt
@HiltAndroidApp
class App : MultiDexApplication() {
...
}
AppComponent.kt
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
@Component.Factory
interface Factory {
fun create(@BindsInstance context: Context): AppComponent
}
}
AppModule.kt
@Module
@InstallIn(ApplicationComponent::class)
open class AppModule {
...
}
MainActivity.kt
@AndroidEntryPoint
public class MainActivity: AppCompatActivity() {
...
}
MainModel.kt
@Singleton
class MainModel @Inject constructor(
@ApplicationContext context: Context
) {
...
}