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
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 { ... }
}