DEV Community

Cover image for DataBindingUtil.inflate vs View Binding Inflate
Vincent Tsen
Vincent Tsen

Posted on • Updated on • Originally published at vtsen.hashnode.dev

DataBindingUtil.inflate vs View Binding Inflate

You can inflate your fragment views either with data binding or view binding. Which one should be used?

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, viewBinding is created automatically. Thus, you don't need to explicitly set the viewBinding true in the build.gradle file.

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 LayoutInflater, layoutId, parent ViewGroup, attachToParent flag.

val binding: FragmenMainBinding = DataBindingUtil.inflate(
    inflater, R.layout.fragment_main, container, false)
Enter fullscreen mode Exit fullscreen mode

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 LayoutInflater parameter.

val binding = FragmentMainBinding.inflate(inflater)
Enter fullscreen mode Exit fullscreen mode

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 build.gradle file.

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?

Summary

DataBindingUtil.inflate data binding method is unnecessary in most cases. The view binding inflate method should be used instead.


See Also

Originally published at https://vtsen.hashnode.dev.

Top comments (0)