Skip to main content

Command Palette

Search for a command to run...

DataBindingUtil.inflate vs View Binding Inflate

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

Updated
2 min read
DataBindingUtil.inflate vs View Binding Inflate
V

I'm a self-taught hobbyist Android developer who loves to build projects and share valuable tips for new Android developers.

Feel free to comment, share or connect with me!

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)

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)

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

Android App Dev

Part 43 of 47

Discover helpful tips and tricks for Android app development and Jetpack Compose through my personal journey and experience.

Up next

2 Ways to Implement Binding Adapters

One way is using function parameter and another way is using extension function.