Search code examples
androiddata-bindingandroid-databinding

Which is the correct way to use / initialize Data Binding in Android


Inside an activity, we can use Data Binding in two ways:

Number One
val binding : PlainActivityBinding = DataBindingUtil.setContentView(this, R.layout.plain_activity)

Number Two
val binding = PlainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)

Both Works, but which one is correct.
Which one we should use ?

Please guide

Note: I have read multiple questions and answers related to this area but could not find any valid answer. Hence, posting this question after doing thorough homework.


Solution

  • Both is correct but have a difference. DataBindingUtil.setContentView return binding associated with the generic type <T> of the generated binding class. Used for example with BaseActivity and multiple inheritors. PlainActivityBinding.inflate return binding associated with PlainActivity