Search code examples
androidkotlinandroid-databindingandroid-jetpack

What is the difference between `bind`, `inflate` and `setContentView` in `DataBindingUtil`


I have seen DataBindingUtil used with all three methods, and it is not clear from the documentation (https://developer.android.com/reference/android/databinding/DataBindingUtil) what the difference is between the three.


Solution

  • bind takes an already inflated view hierarchy and returns a ViewDataBinding for it.

    inflate takes a layout resource ID, inflates a view hierarchy from it and returns a ViewDataBinding for it. It's essentially equal to

    val layoutInflater = LayoutInflater.from(context)
    val view = layoutInflater.inflate(R.layout.some_layout, ...)
    val binding = DataBindingUtil.bind<SomeLayoutBinding>(view)
    

    setContentView takes a layout resource ID, inflates a view hierarchy from it, sets it as an activity content and returns a ViewDataBinding for the inflated view hierarchy. It's essentially equal to

    setContentView(R.layout.some_layout)
    val view = findViewById<View>(android.R.id.content)
    val binding = DataBindingUtil.bind<SomeLayoutBinding>(view)