23

I was wondering what is the difference between the following:

binding = DataBindingUtil.inflate(inflater, R.layout.drawer_item_primary, parent, false);

vs

binding = DrawerItemPrimaryBinding.inflate(inflater, parent, false);

Are there any performance differences?
What is the preferred use case for each?

Any other info would be appreciated!

Thanks!

Bolt UIX
  • 5,988
  • 6
  • 31
  • 58
Francois
  • 10,465
  • 4
  • 53
  • 64

2 Answers2

27

Use Binding class's inflate as recommended in Android Documentation.

In DataBindingUtil class documentation you can see.

inflate

T inflate (LayoutInflater inflater, 
                int layoutId, 
                ViewGroup parent, 
                boolean attachToParent)

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

One option is to inflate by DataBindingUtil but when only you don't have generated binding class.

You have generated binding class, use that class instead of using DataBindingUtil.

In Java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    HomeFragmentBinding binding = HomeFragmentBinding.inflate(inflater, container, false);
    //set binding variables here
    return binding.getRoot();
}

In Kotlin

lateinit var binding: HomeFragmentBinding 
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = HomeFragmentBinding.inflate(inflater, container, false)
    return binding.root
}

If your layout biniding class is not generated @See this answer.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
9

Actually, both the things are working same It will not affect on performances. Only one minor difference which I have noticed is that if you are sure about which layout you want to inflate then you can use

binding = DrawerItemPrimaryBinding.inflate(inflater, parent, false);

But If you want dynamic binding class then you can use

int layoutId = R.layout.drawer_item_primary;
DataBindingUtil.inflate(inflater, layoutId, parent, false);

So DrawerItemPrimaryBinding.inflate(inflater, parent, false); will always return our DrawerItemPrimaryBinding class. where if we have to use DataBindingUtil.inflate(inflater, layoutId, parent, false); then we can cast it as per requirement.

Thank you.

Rujul Gandhi
  • 1,700
  • 13
  • 28