Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Databinding DatabindingUtil vs binding class

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!

like image 705
Francois Avatar asked Aug 17 '18 10:08

Francois


People also ask

What is the difference between databinding and view binding?

View binding and data binding both generate binding classes that you can use to reference views directly. However, view binding is intended to handle simpler use cases and provides the following benefits over data binding: Faster compilation: View binding requires no annotation processing, so compile times are faster.

Is Android databinding deprecated?

Recently Android has announced that with Kotlin 1.4. 20, their Android Kotlin Extensions Gradle plugin will be deprecated and will no longer be shipped in the future Kotlin releases. Android Kotlin Extensions plugin brought with it two very cool features : Synthetics let you replace calls to findViewById with kotlinx.

Can I use both databinding and ViewBinding?

Data binding includes everything that ViewBinding has, so it wasn't designed to work side by side with View binding. The biggest issue is the naming conflict between the generated classes. Both ViewBinding and DataBonding would want to generate the class MainLayoutBinding for the layout main_layout. xml .


1 Answers

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.

like image 86
Khemraj Sharma Avatar answered Oct 07 '22 13:10

Khemraj Sharma