0
0

More than 3 years have passed since last update.

さくっとDaggerをHiltに対応する

Posted at

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
) {
    ...
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0