Search code examples
androidkotlinandroid-viewbinding

ConstraintLayout view binding migration from Kotlin synthetics


I have an existing view that extends from ConstraintLayout which looks something like this:

class LandingTemplate: ConstraintLayout {

  init {
    inflate(context, R.layout.landing_template, this)
    
    // Currently this 'recyclerView' is a kotlin synthetic
    recyclerView.run {
      // this sets up the recycler view
    }
}

I'm familiar with view binding with activities and fragments, but I can't find any documentation around the extends layout case. My question is, what do I replace that initial inflate call with here?


Solution

  • I'm assuming you have a context available from your constructor and your XML layout's top level tag is <merge>. You can use your binding class's inflate to create and add the child layout.

    And since this can all be set up in the constructor, you don't need lateinit var like in the Activity/Fragment examples, and can just use val instead.

    class LandingTemplate(context: Context, attrs: AttributeSet): ConstraintLayout(context, attrs) {
    
        private val binding = LandingTemplateBinding.inflate(LayoutInflater.from(context), this)
    
        init {
            binding.recyclerView.run {
                // this sets up the recycler view
            }
        }
    }