简体   繁体   中英

How to define context in a kotlin object

How can I define a context for the progressdialog within such an object

import dmax.dialog.SpotsDialog

object Constants {
    //These are all the constants within our application
    const val permission_request = 100
    val firebaseAuth = FirebaseAuth.getInstance()
    val progressDialog = SpotsDialog.Builder().setContext(thecontext).build()
}

You can give it a lateinit context property that you set in your Application class. Then make the property that's dependent on it Lazy. But in this case, it doesn't make sense, because a Dialog is transient. It wouldn't be a constant. You can't reuse dialogs, because Android destroys and recreates the Activities/Fragments that host them according to various lifecycle processes.

But if you do have something like a constant that needs a Context, this is how you could do it:

object Constants {
    lateinit var context: Context
    val foo by lazy { Foo(context) }
}

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        Constants.context = this
    }
}

And make sure you set .MyApplication as the Application name in the manifest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM