What is the best way to declare on UI component in android with Kotlin?

前端 未结 3 990
抹茶落季
抹茶落季 2020-11-30 12:22

I\'m trying to build android application using Kotlin for the first time.

I want to declare on some buttons outside the OnCreate method and i can initialize them onl

3条回答
  •  一个人的身影
    2020-11-30 13:10

    You can do it with lateinit as @zsmb13 suggest BUT this has the disadvantage that your views will be variable instead of final. If you want them to be final you can use the lazy property delegation

    By using lazy you can declare how the value will be initialized when you first try to access it so by declaring

    private val btnProceed: Button by lazy {
        findViewById(R.id.yourID)
    }
    

    Whenever you access your btnProceed you will have your activity (this example assume you're using an activity) loaded so you can use that method

提交回复
热议问题