DataBindingUtil.inflate vs View Binding Inflate
You can inflate your fragment views either with data binding or view binding. Which one should be used?
2 min read
If you turn on
dataBinding in your
build.gradle, it is likely you use the "data binding layout".
As mentioned in previous article here, when "data binding layout" is used,
viewBindingis created automatically. Thus, you don't need to explicitly set the
viewBinding truein the
So you have 2 ways to inflate your fragment views in your
onCreateView() - data binding method and view binding method.
1. Data Binding Method
FragmenMainBinding is the view binding class. To inflate fragment view, you need to pass in the
val binding: FragmenMainBinding = DataBindingUtil.inflate( inflater, R.layout.fragment_main, container, false)
Well, that is awesome! Let's look at the second method using View Binding
2. View Binding Method
It is even more simple! You just need to pass in one
val binding = FragmentMainBinding.inflate(inflater)
Which One is Better?
It is obvious that the second View Binding method is better. It can be used either with
dataBinding true or
viewBinding true in your
So why and when
DataBindingUtil.inflate() is needed then? Well, if you look at the official document here, it states that
Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.
My next question is in what scenario the
layoutId is unknown? I don't have the answer because I don't have such use case, do you?
DataBindingUtil.inflate data binding method is unnecessary in most cases. The view binding inflate method should be used instead.
Did you find this article valuable?
Support Vincent Tsen by becoming a sponsor. Any amount is appreciated!