How to use View Binding on custom views

If you are trying to use View Binding with the root view, this is working for me:

class CustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private lateinit var binding: CustomViewBinding

    override fun onFinishInflate() {
        super.onFinishInflate()
        binding = CustomViewBinding.bind(this)
    }
}

Just inform the root, and whether you want to attach to it

init { // inflate binding and add as view
    binding = ResultProfileBinding.inflate(LayoutInflater.from(context), this)
}

or

init { // inflate binding and add as view
    binding = ResultProfileBinding.inflate(LayoutInflater.from(context), this, true)
}

which inflate method to use will depend on the root layout type in xml.


You can initialize the view binding property right away

private val binding = CustomViewBinding.inflate(LayoutInflater.from(context), this)

To use the view binding, you need to use the generated binding class not the LayoutInflater, for example, if the layout name is result_profile.xml then you need to use ResultProfileBinding as:

class CustomView @kotlin.jvm.JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private lateinit var binding: ResultProfileBinding

    init { // inflate binding and add as view
        binding = ResultProfileBinding.inflate(LayoutInflater.from(context))
        addView(binding.root)
    }

}
  1. Auto generated class : result_profile.xml -> ResultProfileBinding(name of layout, appended with Binding )
  2. Inflate the binding

    ResultProfileBinding.inflate(LayoutInflater.from(context))
    
  3. Use addView to add the view in the hierarchy as:

    addView(binding.root)
    

Note: If you are extending from ConstraintLayout(is the parent class) then use constraint set