The official Google dependency injection framework, based on dagger
Add and use
Add hilt dependencies to build.gradle in project
Add the version number of Hilt to the top build.gradle
Buildscript {ext.kotlin_version = '1.3.61' ext.hiltversion = '2.28-alpha'..... Dependencies {classpath 'com. Android. View the build: gradle: 3.5.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "com.google.dagger:hilt-android-gradle-plugin:$hiltVersion" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }Copy the code
- Add version of hilt,
Ext hiltVersion = '2.28 alpha'
- Add the Gradle plugin
classpath "com.google.dagger:hilt-android-gradle-plugin:$hiltVersion"
Add plug-ins and dependencies to your app’s build.gradle
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
implementation "com.google.dagger:hilt-android:$hiltVersion"
kapt "com.google.dagger:hilt-android-compiler:$hiltVersion"
Copy the code
Tag your custom application with the @hiltAndroidApp tag
@HiltAndroidApp
class MyApplication : Application() {
...
}
Copy the code
Now that the basic configuration is complete, all you need to do is label the place where you want to use it.
Few understand
@ Inject label
Inject the @inject tag serves two purposes: field indicates that the field needs injection, and constructor indicates that the constructor provides the object to Inject
@ InstallIn understanding
Here is mainly for those who cannot add @ the class to provide instances of inject annotation to the constructor, and then provide the instance needs to have a similar life cycle, or reference permissions, this annotation is to limit these generated object for the life cycle, the document in the word to the container, the understanding is right.
Use this method if you cannot annotate constructor directly@Module
To provide object generation
Codelabs.developers.google.com/codelabs/an…
Possible problems
Error reported when used with Arouter
public final class MainFragment BaseFragment {
^
Expected @AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin?
[1;31m[Hilt] Processing did not complete. See error above for details.[0m
Copy the code
If you are a pure Kotlin project, you can simply remove the compileOptions so there are no conflicts.
Android {compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig {applicationId "XXXX" minSdkVersion 19 29 versionCode targetSdkVersion 4 versionName testInstrumentationRunner 1.1.2 "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true // javaCompileOptions { // annotationProcessorOptions { // arguments = [AROUTER_MODULE_NAME: project.getName()] // } // } }Copy the code
Reference answer: stackoverflow.com/a/62619732/…
Reference Documents:
- Codelabs:codelabs.developers.google.com/codelabs/an…
- Android official document: developer. The android. Google. Cn/training/DE…