https://developer.android.com/training/dependency-injection/hilt-android
In project level build.gradle
file
buildscript {
ext.dagger_version = "2.38.1"
// ...
dependencies {
// ...
classpath "com.google.dagger:hilt-android-gradle-plugin:$dagger_version"
}
}
In app level build.gradle
file
plugins {
// ...
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
// ...
dependencies {
// ...
implementation "com.google.dagger:hilt-android:$dagger_version"
kapt "com.google.dagger:hilt-compiler:$dagger_version"
}
- Create application class and add
@HiltAndroidApp
annotation.@HiltAndroidApp class BaseApplication: Application() { }
- Add to manifest.
<manifest ... > <application android:name=".BaseApplication" ... > ... </application> </manifest>
- Activities / Fragment / Service / custom views, i.e. all android framework receiving an injection needs the
@AndroidEntryPoint
annotation@AndroidEntryPoint class MainActivity: AppCompatActivity() {
- The
lateinit var
into which injection is performed@Inject
annotation.@Inject lateinit var testClass: TestClass
- The source class, whose instance is being injected, must also have the
@Inject
annotation above its constructor.class TestClass @Inject constructor() { ... }
@AndroidEntryPoint class MainActivity: AppCompatActivity() { @Inject lateinit var testClass: TestClass override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) println("Result: ${testClass.getSampleString()}") } } class TestClass @Inject constructor() /* * Note that even though the constructor is empty (constructor would not have been normally needed), * but since we are using dependency injection, we need the @Inject annotation, on a contructor. */ { fun getSampleString() = "A sample string" }
Almost same as above. Add @Inject
annotation above the constructor where the injection is to be performed.
@AndroidEntryPoint class MainActivity: AppCompatActivity() { @Inject lateinit var testClassAdd: TestClassAdd override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) println("Result: ${testClassAdd.getStringAddition()}") } } class TestClassAdd @Inject // CONSTRUCTOR INJECTION constructor(private val n1: RandomNumberClass, private val n2: RandomNumberClass){ fun getStringAddition() = "Number 1: ${n1.value}, Number 2: ${n2.value}, Addition: ${n1.value + n2.value}" } class RandomNumberClass @Inject constructor() { val value = (Math.random()*100).toInt() }
The source class (in the above example RandomNumberClass
) cannot have constructor arguments.
Check Part 2