我目前正在学习如何使用Dagger 2注入Android应用程序。我编写了非常基本的代码,但是它无法正常工作。我的目标是按原样注入MainActicity。它建立 我的代码:
class MainActivity : AppCompatActivity() {
@Inject lateinit var info: Info
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txt_view.text = info.textInformation
}
}
class Info {val textInformation = "You are able to read this" }
@Module
class InfoModule{
@Provides
fun info ():Info{
return Info()
}
}
class CustomApp : Application (),HasActivityInjector{
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
override fun activityInjector(): AndroidInjector<Activity> {
return dispatchingAndroidInjector
}
}
@Component(modules = arrayOf(AndroidInjectionModule::class,
ActivityModule::class))
interface ApplicationComponent{
fun inject(application: CustomApp)
}
@Module
abstract class ActivityModule{
@ContributesAndroidInjector(modules = arrayOf(InfoModule::class))
abstract fun contributeInfoActivityInjector():MainActivity
}
答案 0 :(得分:1)
答案是我忘记将此代码添加到CustomApp类,而将.CustomApp添加到清单文件
override fun onCreate() {
super.onCreate()
initDi()
}
private fun initDi() {
DaggerApplicationComponent.builder().build().inject(this)
}