Static way to get 'Context' in Android?

前端 未结 19 2701
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  执念已碎
    2020-11-21 07:25

    Kotlin way:

    Manifest:

    
    
    
    

    MyApplication.kt

    class MyApplication: Application() {
    
        override fun onCreate() {
            super.onCreate()
            instance = this
        }
    
        companion object {
            lateinit var instance: MyApplication
                private set
        }
    }
    

    You can then access the property via MyApplication.instance

提交回复
热议问题