解决方案1:
class App : Application() {
private var movieAppComponent: MovieAppComponent? = null
companion object {
private var app: App? = null
fun getApp(): App? {
return app
}
}
override fun onCreate() {
super.onCreate()
app = this
movieAppComponent = DaggerMovieAppComponent.builder()
.applicationModule(ApplicationModule(this))
.netModule(NetModule(Keys.BASE_URL, this))
.build()
}
fun getMovieAppComponent(): MovieAppComponent? {
return movieAppComponent
}
}
解决方案2:
不需要创建这样的方法。您可以在活动中使用类型转换:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as? App)?.getMovieAppComponent()?.inject(this)
}
}