Kotlin Singleton Application Class

前端 未结 4 891
梦毁少年i
梦毁少年i 2021-01-31 07:56

So in android i want to make my application class a singleton.

Making it like this:

object MyApplication: Application(){}

won\'t work.

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 08:36

    If you want to use it to access some static properties you have there: You will only have one instance of your Application, so simply use the name you gave to the class. Don't worry about it not being an actual singleton, you can use it the same way.

    Example:

    class MyApp : Application() {
    
        companion object {
            const val CONSTANT = 12
            lateinit var typeface: Typeface
        }
    
        override fun onCreate() {
            super.onCreate()
            typeface = Typeface.createFromAsset(assets, "fonts/myFont.ttf")
        }
    
    }
    

    Then you can use MyApp.CONSTANT and MyApp.typeface anywhere in your app.

    -

    If what you want is to use it as an application context you can create an extension property for Context:

    val Context.myApp: MyApp
            get() = applicationContext as MyApp
    

    Then you can use myApp to get the the application context anywhere you have a context.

提交回复
热议问题