As Android Developers, we write business logic in Kotlin or Java and design the UI with XML (for now though, Jetpack Compose is coming ๐). At some point, we always want to get references to UI elements from Kotlin/Java code to manipulate their behavior. Initially, the findViewById()
method was provided to help in this case but it became ineffective as errors relating to NullPointerExceptions
may occur and crash our app, the number of code lines required to get references to views in bigger apps is also overwhelming.
Data binding and View binding were introduced to help us say goodbye to findViewById()
, but what are the differences between them? ๐
Comparison
While Data binding and View binding generate binding classes that provide access to views directly, they are different in the following ways:
Speed: View binding is faster in terms of compilation speed because it requires no annotation processing.
Ease of Use: In terms of use, enabling View binding in a module is enough to enable view binding automatically in all layout files of the module as it does not require the addition of the <layout>...</layout>
tags unlike data binding making it easier to use.
Binding expressions: Using binding expressions within layout files is not supported with view binding as binding expressions are advanced features that are only supported with data binding.
Two-way data binding: One-way data binding allows us to set values on views (e.g TextView), in addition to this, two-way data binding allows us to set or get values from views (e.g CheckBox, EditText) and manipulate them, view binding doesn't support two-way data binding as it is also an advanced feature that only data binding supports.
Impact on APK Size: Apps built with data binding are usually larger because internally, in addition to data binding files, view binding files are also generated alongside because data binding can do everything that can be done with view binding.
Conclusion
Considering the differences between data binding and view binding, the way we make use of each of them depends on what feature or behaviour we are trying to implement within our app and what works best for us as Android developers. Both of these are ways that help us build more robust apps and using at least one of them is important.
References
This is my first article, if you found it useful, do not hesitate to like and share as others may find it useful as well. If you have questions or feedbacks for me, kindly drop them in the comments or send me a direct message on Twitter.