【问题标题】:How to access Application class variables in activity in kotlin android如何在 kotlin android 的活动中访问应用程序类变量
【发布时间】:2019-07-21 04:06:41
【问题描述】:
  • 我曾经通过使用 java中的公共方法
  • 如何使用 kotlin 做同样的事情

App.kt

class App : Application() {


    private var app: App? = null
    private var movieAppComponent: MovieAppComponent? = null

    override fun onCreate() {
        super.onCreate()
        app = this

        movieAppComponent = DaggerMovieAppComponent.builder()
            .applicationModule(ApplicationModule(this))
            .netModule(NetModule(Keys.BASE_URL, this))
            .build()
    }

    fun getApp(): App? {
        return app
    }

    fun getMovieAppComponent(): MovieAppComponent? {
        return movieAppComponent
    }

}

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
        App.getApp().getMovieAppComponent().inject(this)
    }



}

错误:

App.getApp().getMovieAppComponent().inject(this)

这里getApp() 我得到了未解决的参考

【问题讨论】:

  • 因为 getApp 是一个非静态方法 .. 使 app 静态与 Companion 块 ..
  • @ADM .... 你能把它显示为答案,所以我可以接受它

标签: android kotlin


【解决方案1】:

解决方案 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:

不需要创建这样的方法。您可以在 Activity 中使用类型转换:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
        (application as? App)?.getMovieAppComponent()?.inject(this)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2018-09-28
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多