Android ViewBinding with CustomView

ViewDataBinding.inflate doesn't generate of child view accessor inside custom view.

thus, you can't touch line1(TextView) via only use ViewDataBinding.

If you don't want using findViewById or kotlin synthetic, MyCustomView also needs to apply ViewDataBinding. try as below.

CustomView

class MyCustomView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private val binding =
        CustomLayoutBinding.inflate(LayoutInflater.from(context), this, true)

    val line1
        get() = binding.line1

    val line2
        get() = binding.line2
}

MainActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
    setContentView(binding.root)

    with(binding.customView) {
        line1.text = "Hello"
        line2.text = "World"
    }
}

Another approach is to return the CustomView binding object.

class CustomView constructor(context: Context, attrs: AttributeSet?) : 
    ConstraintLayout(context, attrs){
                
        private val _binding: CustomViewBinding = CustomViewBinding.inflate(
                        LayoutInflater.from(context), this, true)
                
                val binding get() = _binding    
        }

And then in your Activity or Fragment:

binding.customView.binding.line1?.text = "Hello"
binding.customView.binding.line2?.text = "World"