关于android:Hilt多模块项目实现一

本文适宜有肯定的Dagger2应用根底的同学

上一篇:dagger.android多模块我的项目实现(二)
下一篇:[Hilt多模块我的项目实现(二)]()

前两篇咱们讲了dagger.android在多模块我的项目中的用法能够看到dagger.android让Android我的项目依赖注入变得更简略。但这还不是最简略的,android官网最近又给出了一个新的Hint。它是dagger.android的升级版,当初还只是alpha版,Hilt 应用起来超级简略,不须要咱们定义任何Component,只须要Module就能够了。

单个模块的我的项目按官网做就能够,多模块我的项目中,一般多模块我的项目和单模块我的项目没有区别,本篇咱们先讲下一般多模块我的项目的实现。

咱们在dagger.android多模块我的项目(一)的根底上革新实现

所有Component都删掉,只留下Module和Activity就能够了

先增加Hilt依赖

在我的项目build.gralde中加上

buildscript {
    dependencies {
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.29-alpha'
    }
}

在所有应用到Hilt的模块的build.gralde中加上,这里有点比拟奇怪按理hilt-android用api办法引入放在base模块就能够的,然而这样却会报错,兴许是Hilt的一个bug吧。

apply plugin: 'com.android.application'
//apply plugin: 'com.android.library'

apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

dependencies {
    implementation "com.google.dagger:hilt-android:2.29-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.29-alpha"
}

app模块:

在AppApplication加上一个@HiltAndroidApp注解,留神不要加到BaseApplication下来了

@HiltAndroidApp
class AppApplication : BaseApplication() {
}

AppModule加上一个@InstallIn(ApplicationComponent::class) 这个代码AppModule为ApplicationComponent提供依赖

@Module
@InstallIn(ApplicationComponent::class)
class AppModule {

    @IntoSet
    @Provides
    fun provideString(): String {
        return "app"
    }
}

user,news模块:

UserModule、NewsModule加上一个@InstallIn(ActivityComponent::class) 这个代码示意UserModule、NewsModule为ActivityComponent提供依赖

@Module
@InstallIn(ActivityComponent::class)
class NewsModule {

    @IntoSet
    @Provides
    fun provideString(): String {
        return "news"
    }
}

@Module
@InstallIn(ActivityComponent::class)
class UserModule {
    @IntoSet
    @Provides
    fun provideString(): String {
        return "user"
    }
}

UserActivity、NewsActivity加上一个@AndroidEntryPoint,这代表这个Activity须要Hint注入对象,留神,这个不能够加在BaseActivity上,这样做没用,只能加在最终页面上

@AndroidEntryPoint
class NewsActivity : BaseActivity() {

    @Inject
    lateinit var set: Set<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_news)
        text.text = set.toString()
    }
}
@AndroidEntryPoint
class UserActivity : BaseActivity() {

    @Inject
    lateinit var set: Set<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user)
        text.text = set.toString()
    }
}

到这里Hilt注入就实现了,是不是超级简略

代码地址

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理