Dependency Injection is the first step you have to take towards building an app that can be tested. So today we will use Hilt to introduce view model injection into a Fragment. If you wish to carry along with this article you can checkout the starting code here
依赖注入是构建可测试应用程序的第一步。 因此,今天我们将使用Hilt将视图模型注入片段中。 如果您希望继续阅读本文,可以在此处签出起始代码
设置击剑 (Setting up Hilt)
First of all we need to add dependencies.
首先,我们需要添加依赖项。
Add the hilt-android-gradle-plugin
plugin to your project's root build.gradle
file:
将hilt-android-gradle-plugin
插件添加到项目的根build.gradle
文件中:
buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
}
Then, apply the Gradle plugin and add these dependencies in your app/build.gradle
file:
然后,应用Gradle插件并将以下依赖项添加到您的app/build.gradle
文件中:
...
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
dependencies {
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha02"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02"
}
Hilt uses Java 8 features. To enable Java 8 in your project, add the following to the app/build.gradle
file:
Hilt使用Java 8功能 。 要在项目中启用Java 8,请将以下内容添加到app/build.gradle
文件中:
android {
...{
sourceCompatibility = 1.8
targetCompatibility = 1.8}kotlinOptions {
jvmTarget = "1.8"}