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!
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With