Home > Software engineering >  Kotlin how to make a ViewBinding by viewBindings() similar to ViewModel by viewModels()
Kotlin how to make a ViewBinding by viewBindings() similar to ViewModel by viewModels()

Time:05-03

In Kotlin there is this nice extension function that allows us to write

var viewModel: MyViewModel by viewModels()

Is it possible to have the same thing for ViewBindings? Currently I am using this (in Activities):

var viewBinding: MyViewBinding by lazy { MyViewBinding.inflate(layoutInflater) }

It works but feels a bit clumsy. I'd rather have it like the following but do not know how to implement that:

var viewBinding: MyViewBinding by viewBindings()

CodePudding user response:

For sure you can write a property delegate for a viewbinding for any class that holds views. You can check out this library for inspiration, or even use it in your project

  • Related