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

前端 未结 3 982
抹茶落季
抹茶落季 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 12:53

    Instead of using lateinit, you can also do lazy initialization:

    private val button by lazy {
        findViewById(R.id.button) as Button
    }
    

    The first time you access the button property, it will execute the block once and use the result for future calls. In onCreate for example, you can now directly access it:

    fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(bundle)
      setContentView(R.layout.my_view)
    
      button.setOnClickListener { ... }
    }
    

提交回复
热议问题