apply plugin: 'com.android.application'
...
apply plugin: 'kotlin-kapt' // kapt 插件
...
kapt {
generateStubs = true
}
dependencies {
...
implementation 'com.google.dagger:dagger:2.12' // Dagger 2 依赖
implementation 'com.google.dagger:dagger-android-support:2.12' // Dagger 2 Android 支持包
kapt 'com.google.dagger:dagger-compiler:2.12' // Dagger 2 注解处理
}
@Subcomponent(modules = arrayOf(...)) // 没有其他 Module 圆括号可省略
interface YourActivitySub : AndroidInjector<YourActivity> {
@Subcomponent.Builder
abstract class Builder : AndroidInjector.Builder<YourActivity>()
}
@Module(subcomponents = arrayOf( YourActivitySub::class))
// 每新建一个 Activity,都要新建相应的 ActivitySub 接口,并添加到这里
abstract class ActivityModule {
@Binds // 每新建一个 Activity,都要添加一个相应方法,方法名不能相同
@IntoMap
@ActivityKey(YourActivity::class)
abstract fun bindYourActivity(builder: YourActivitySub.Builder): AndroidInjector.Factory<out Activity>
}
@Singleton // 如果有 Module 使用了该注解实现单例模式,这里也需要添加
@Component(modules = arrayOf(
ActivityModule::class, // 注入 Activity 的 Module
FragmentModule::class, // 注入 Fragment 的 Module
...
AndroidSupportInjectionModule::class)) // 确保 DaggerApplication、DaggerActivity、DaggerFragment等所有类型可用
interface ApplicationSub : AndroidInjector<MyApplication> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<MyApplication>()
}
class MyApplication : DaggerApplication() { // 如果项目中使用了 v4.Fragment 要继承 support 包下的 DaggerApplication
override fun applicationInjector() : AndroidInjector<out DaggerApplication> {
return DaggerApplicationSub.builder().create(this) // 编译后生成
}
}
dependencies {
...
implementation 'com.google.dagger:dagger:2.12' // Dagger 2 支持
implementation 'com.google.dagger:dagger-android-support:2.12' // Dagger 2 Android 支持
kapt 'com.google.dagger:dagger-compiler:2.12' // Dagger 2 注解处理
kapt 'com.google.dagger:dagger-android-processor:2.12' // Dagger 2 注解处理 Android 支持
...
}
@Module // 不需要再为每个 Activity 新建对应的 Subcomponent,不必再添加到这里
abstract class ActivityModule {
@ContributesAndroidInjector
abstract fun contributeYourActivity() : YourActivity
}
// Kotlin 提供的方法,能简单快速的生成一个数组
val array = arrayOf("1", "2") // 与之类似的还有 arrayListOf() 、 setOf() 等,以后详细说明
// 类对象
A::class // 相当于 Java 中的 A.class,同时还有 A.javaClass 相当于 Java 中的 A.getClass()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有