Android databinding vs viewbinding

Android: разница между DataBinding и ViewBinding

Мы используем DataBinding с момента выпуска Jetpack. В документации Android указано, что ViewBinding был добавлен в Android Studio 3.6 Canary 11+ .

У меня есть настоящая документация, но она похожа на DataBinding.

Кто-нибудь может объяснить, как мы можем различать эти два понятия?

2 ответа

DATABINDING = привязка DATA (из кода) к представлениям + привязка к представлению (BINDING представления к коду)

VIEWBINDING = BINDING VIEWS только для кода

При привязке вида макеты не нуждаются в теге макета

Вы не можете использовать привязку вида для связывания макетов с данными в XML (Нет выражений привязки, нет BindingAdapters или двусторонней привязки с привязкой просмотра)

Основными преимуществами видообразования являются скорость и эффективность. Он имеет более короткое время сборки, поскольку позволяет избежать накладных расходов и проблем с производительностью, связанных с привязкой данных, поскольку процессоры аннотаций влияют на время сборки привязки данных.

Короче говоря, ничто не может сделать привязка просмотра, которую не может сделать привязка данных (хотя за счет более длительного времени сборки), и есть много привязки данных, которая может сделать привязку данных

Сравнение с привязкой данных

Привязка представления и привязка данных генерируют классы привязки, которые можно использовать для прямой ссылки на представления. Однако привязка представлений предназначена для обработки более простых вариантов использования и обеспечивает следующие преимущества по сравнению с привязкой данных:

И наоборот, привязка представления имеет следующие ограничения по сравнению с привязкой данных:

Из-за этих соображений в некоторых случаях лучше использовать как привязку вида, так и привязку данных в проекте. Вы можете использовать привязку данных в макетах, которые требуют расширенных функций, и использовать привязку видов в макетах, которые этого не делают.

Источник

DataBinding vs ViewBinding (Simple Comparison)

Apr 21, 2020 · 3 min read

In Android Development, every single time wants to access our layout, we always using `findViewById` to define our layout inside java/kotlin class and use correctly name to accessing or got crash when running the apps, but since android jetpack launch new feature that called “DataBinding”, developers have another option to define layout inside the java/kotlin class. And at least save you from expensive initialize layout and remove boilerplate and think its time to say Goodbye for `findViewById`.

After the jetpack launch, Android Studio 3.6 release new feature and called “ ViewBinding”, and developers think

And we h ave some question between using Viewbinding and Databinding

  • What difference implementation between them
  • Is that any impacting to size

What difference implementation between them

First, we must enable this in our app build.gradle

and check your Gradle version, I preferably recommended with version 3.5 or higher for Databinding and ViewBinding, Then catch up with your layout add this part when using DataBinding

Then, how when we implement ViewBinding?

Just remove tag on the above layout

Yep, we don’t use ViewBinding, because on DataBinding we must add that layout tag to generate Binding class and it’s different with ViewBinding which automatically generates all layout to Binding class.

Okay, let’s go to MainActivity, below this for implementation DataBinding

and it’s an implementation using ViewBinding

All Binding class will be generated with a format below

Different between them is how to initialize that,

Is that any impacting to size

I start to build APK between them, doing some comparison ( note: deactivate minify) and if you wanna see what I build visit my simple project here

There are different size apk 50kb between them and start to use analyze APK to check every part of them and I found inside classdex on androidx directory between DataBinding and ViewBinding generate the same directory except this

Remember, this is a simple project and maybe if you implement this on your complicated app. it makes a huge impact for your size APK/AAB ( Android App Bundles).

Databinding and ViewBinding have different to implement and had an impact of size APK between them. 50 kb it’s important for our application despite we implement minify and R8 to reduce for our app and consider between using Databinding and Viewbinding for your app. it’s also worth using one of them to prevent a crash on your app and says

If you find this article useful please don’t hesitate to share it and give applause. If you have questions or would like to give me some feedback, please comment below or follow my social media ( Twitter, Linkedin).

Источник

Android: Accessing view, now what? (butterknife, viewbinding, databinding comparison)

Hey guys! It has been a while since the last post, hope you guys have been doing good and staying strong:)

Recently, I have come across multiple ways to access layouts and bind those views with code so that we can use that views as we want. Sounds like we are going into the topic too straight away?

Well let me put this way, I have a xml file which has text field. In one of the fragments that I have, I want to set the text value or even decide on the visibility of the text field. Sounds like I should get the instance of the view in my fragment class. Then how do we do it? how do we create a bridge/connect these two seperate files and use one property in the other class?

Читайте также:  Plague inc full для android

well again, like I said word «multiple» earlier, there are many. And needless to say if you are working on a exisiting project that has been there for a while, you might probably have come across the history of view binding in Android development(with a bit of exaggeration):)

In this article, we will cover an overview of some of the most common and well used ways to make above possible in Android Development and talk about the general concept and some of the points that we can take into our accounts going forward.
Especially, if you are trying to migrate or transit the way of it from old way to another way, then hopefully this article can give you a good insight.

Step1: What are there for us

There are five most common and well-known ways to do view binding.

I am sure that most of you are already aware of some of or all of these view binding libraries and possibly already been using it for a while. I am not going to go through each and every item and explain since it is just all about high level of the concept of view binding ways and just to give it a good understanding as myself was also confused since there were so many! (as you can see a bit of a frustration from the title «now what!»)

A. FindViewByID

Here we go, we have the most traditional and oldest way to bind views here. Initially, the traditional steps to take to be able to bind views with code is something like this.

  1. Inflate the XML
  2. Find the required element from the XML
  3. Assign it to a local/member variable
  4. Get the value from data
  5. Assign the value or Assign the event listener

On the second step when finding the required element from the XML, using this old way would required to code «findViewById», creating unnecessary boilerplates.This approach is being considered as outdated way and better to avoid to use.

B. Butterknife


Butterknife was introduced in 2016 by Jake Wharton ever since its release, it had been considered one of the most best ways to replace «FindViewByID» since it was reducing a lot of boilerplates codes that original way was producing.
In butterknife, there are Annotate fields with @BindView and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout like above.

However, the story doesn’t end here
Guess what,
Butterknife tool is now deprecated and feature development and general bug fixes have stopped as the author himself is recommending to switch to «viewbinding» which will be covered in this article later.(FYI, this author has now joined the team to work on viewbinding tool now).
If you are interested to have a look at some documentations. check out this link.
https://github.com/JakeWharton/butterknife

C. Kotlin Synthetic

While butterknife was considered one of the best ways to do viewbinding. We also need to have a look at this one called Kotlin Syntehtic(also called Kotlin extensions). This one is, still in a lot of places, being considered the best way to do viewbinding for kotlin classes.

Why?
Kotlin uses synthetic properties, and they are called on demand with a caching function (hence a small activity / fragment load), and ButterKnife binds all the views at the same time ButterKnife.bind() (which consumes a bit more time). With Kotlin you don’t even need to use annotation to bind to views.
Just use the id of the imported views.

Yes, it also goes well with the RecyclerView + ViewHolder template, you just need to import kotlinx.android.synthetic.main.layout_main.view.* (If layout_main.xml is the name of the Activity / Fragment layout file).

You do not need to make any extra effort to import the layout with include .
Just use the id of the imported views.

Sounds good so far?
You are about to see more fascinating stuff

D. ViewBinding VS Databinding

Here is why I wanted to explain viewbinding and databinding together.

As you can see, viewbinding is a sort of subset of databinding libraries which means viewbinding and databiding can do the same jobs in terms of binding layouts. And it would also mean with databinding, you might not need viewbinding cause it will do what viewbinding is supposed to do and also provide a bit of an extra functionalities such as 2way binding, and using variables in xml files.

then, this can lead to a question
«Then let’s just use databinding as it sounds much more fancy!»

Hold on. As much as it sounds fancy, it is pretty heavy loaded library which might cause a longer compile time. So if you are not going to use databinding only functionalities then might be better consider viewbinding as it does have some advantages in terms of build time and apk size.

Also, apparently there are different steps need to take whenever using viewbinding functionalities with actual viewbinding library and databinding libarary.
Here are some examples.

** Adding tag in xml file
When we try to bind layouts using databinding, we need to go to that specific layout file and have to add tag manually to be able to get the generated binding class which I know a lot of developers hate to do.

Читайте также:  All application free android

** DataBindingUitil vs ActivityMainBinding(this one depends on the layout file name for example if the layout name is layout_login_fragment, it will be LayoutLoginFragmentBinding)

if we are using these in Activity this will be inside of onCreate, if it is Fragment it will be inside of onCreateView .

And some simple comparison between all the libraries mentioned above.

We have covered briefly about viewbinding ways on a high level in this article. Hopefully it gives you a better understanding of accessing views in Android and a bit of idea on which way that you will implement based on comparison here.

If it is possible, would love to dig in on viewbinding and databinding a bit more and write something up on how to implement it or even replace one with the other.

Источник

Evolution of Finding Views by ID in Android

The findViewById() vs Butterknife vs Kotlin Synthetics vs DataBinding vs ViewBindings

For more than a decade, Android developers have struggled with a simple but annoying issue. Getting the view reference from XML layouts to their view classes such as Activity or Fragments in entirely separate language — Java or Kotlin.

As a beginner in Android, I used to get confused a lot. The Android SDK provided a method: findViewById() . Functionality-wise, this method performs a singular task — it will give you the reference to the view in XML layouts by searching its ID. And if nothing is found, it will give you the good old NULL , which is said to be the 1-billion dollar mistake by its creator.

In this article, I am going to discuss on how the findViewById() evolved over time and what’s the best approach in “modern Android development” to get the view reference from XML layouts.

The findViewById() method

Obviously, the first one is the findViewById() method. Introduced in the API level 1, this requires an ID and returns a View object.

There are some problems with this approach.

If there is view with this ID in this layout, you won’t get any compile time errors. Rather you will get NullPointerException at runtime when Android fails to locate the view in Activity , Fragment or ViewGroup .

If the view is TextView in XML layout and you are type-casting it as Button , you won’t get any compile time errors. Instead you will get ClassCastException as a TextView cannot be converted to Button .

This method was used extensively and is being used as well throughout whole evolution of Android SDK. In the API level 26 of compileSdk , the definition of this method was slightly changed to remove the casting issue.

Now, developers don’t need to cast their views manually in the code. If you are referencing a Button with a TextView ID, then Android SDK will try to find the Button with the provided ID and it will return NULL because it won’t be able to find it.

But in Kotlin, you would still need to provide the type like findViewById

(R.id.txtUsername) . This may give you NullPointerException if you are not checking your views for null-safety, but this method will not throw ClassCastException like it used to.

Analysis

Type-safe: Before API 26, there was no type-safety.

Null-safe: No null-safety. You will have to check views before accessing for null values.

Boilerplate Code: A lot. You have to declare a separate variable for all the views you need from XML layouts.

Build-time: No difference in build time.

Languages: Supports both Java and Kotlin.

Butterknife

Many different libraries have tried to simplify the findViewById() usage with different methods. Particularly, the Butterknife library created by Jake Wharton has become super famous and has got huge interest by developers around the world. It has become to sort-of standard way to avoid the findViewById usage.

The library uses annotation-processing and fetches the views from XML layouts using the findViewById method under the hood through code generation. It’s very easy to use, and helps in reducing the boilerplate code for developers.

It has almost similar issues as findViewById . However, it adds a null-safety check at runtime to avoid the NullPointerException .

Attention: This tool is now deprecated. Please switch to view binding. Existing versions will continue to work, obviously, but only critical bug fixes for integration with AGP will be considered. Feature development and general bug fixes have stopped. —** Source: Butterknife Github repository**

Analysis

Type-safe: No type-safety as it uses findViewById .

Null-safe: The library checks the views for null-ability at runtime before accessing.

Boilerplate Code: Reduces the boilerplate as annotation processors auto generate code for you.

Build-time: Build time is affected because of annotation processing.

Languages: Supports both Java and Kotlin.

Kotlin Synthetics

Android SDK is now the Kotlin-first officially. That means that Android SDK will implement APIs from the Kotlin language perspective first and later these will be added for Java.

One of the biggest features Kotlin introduced is Kotlin Extension Methods. And with the help of it, Kotlin Synthetics came into existence. Kotlin Synthetics provides developers direct access to their views from XML layout through the auto-generated Kotlin extension methods.

Kotlin Synthetics calls findViewById method once and then caches the view instances in a HashMap by default. This cache configuration can be changed to SparseArray or no cache via the Gradle settings.

Читайте также:  Собрать лаунчер для андроид

Overall, Kotlin Synthetics is a good option as it is type-safe and requires null check through Kotlin’s ? operator if the view is present only in some layout configurations. It requires no extra code from the developers. But this is only supported for Kotlin projects.

But there’s a slight problem which lots of developers have faced with using Kotlin Synthetics. For example, if you set your content view to a layout, then type an ID that only exists in a different layout, the IDE lets you autocomplete and add the new import statement. Unless the developer specifically checks to make sure their import statements only import the correct views, there is no safe way to verify that this won’t cause a runtime issue.

Analysis

Type-safe: Absolutely

Null-safe: Normally its null safe. But if view ID is also present / missing in other layouts, then it requires developer to explicitly either use safe call operator ? or check the variable before use. Developers can use view from other layout leading to NullPointerException .

Boilerplate Code: No boilerplate code as extension methods are generated. It only requires to apply android-kotlin-extension plugin in the build.gradle one time.

Build-time: No difference.

Languages: Supports only Kotlin.

Data Binding

Data Binding Library is a support library that enables you to bind UI elements in your layouts to data sources in your app using a declarative style rather than programmatically.

The Data Binding is much superior in terms of functionality from other approaches as it not only gives you the type-safe AND null-safe view references but also allows you to map your data with views directly inside the XML layouts.

You will have to manually convert layouts to support data binding by nesting in tag.

Now, Android Studio will generate classes for your layouts. For example, if your layout file name is activity_main.xml , then Android will generate a class ActivityMainBinding either in Java or Kotlin as per your preferences. You can use that to access the views without any NullPointerException or ClassCastException .

The best advantage of using Data Binding is that it allows developers to map data with the views in XML without even accessing those in the Java/Kotlin files. You can also use two-way binding to update your XML or data value without any listeners or callbacks.

Analysis

Type-safe: Absolutely

Null-safe: Absolutely

Boilerplate Code: Requires each layout file to be nested inside tag. And also you will have to create instance of auto generated binding class and inflate it to your Activity or Fragment .

Build-time: Increases build time as it generates class files of layouts. Often time, it’s slow because you will have to manually press “Make” button to update / generate new classes for your layouts.

Languages: Supports both Java and Kotlin.

View Binding

The ViewBinding introduced in Android Studio 3.6 recently is sort-of subset of the Data Binding library. It improves build times because no annotation processing is required. It doesn’t require any extra attention to layout files by nesting those in tags. It simply works on all layout files by default.

The only difference with data binding of this is that this is only used for view references. It doesn’t do any data mapping or two-way data binding.

You can use ViewBinding in place of other options if you are simply looking for a good approach to get views from layout files.

This only works on Android Studio 3.6 or later versions. You can enable it by adding this in your app’s build.gradle file.

Then Android Studio will generate View Binding classes for all your layout files. You can use those classes to inflate in the Activity or Fragments just like you would do in Data Binding.

If you want some layout file to be skipped for view binding class, you can do so by adding tools:viewBindingIgnore=»true» in your layout files.

Analysis

Type-safe: Absolutely

Null-safe: Absolutely

Boilerplate Code: No boilerplate code as View Binding classes are generated automatically. It only requires enable the View Binding in the build.gradle one time.

Build-time: No impact on build speed. View Binding* is designed to solve the performance issue connected to using Data Binding *so it doesn’t have a negative impact on the build speed.

Languages: Supports both Java and Kotlin.

Time to Make a Decision

Looking at all the options and their analysis, View Binding is the best option at this time to use.

At the end, please Subscribe to my newsletter DroidUp to get more tutorials and tips on Android development directly in your inbox.

If you liked this article, you can read my new articles below:

Defending Your In-Background App When Android OS Kills It

Android OS will kill your app in background to reclaim the resources and memory. Learn how to handle it as a developer. It all started from a crash reported in Firebase Crashlytics console.

March 19, 2020

How to Display Dependency Tree of Your Android Project with Gradle?

For Starters, simply run the command “gradlew :app:dependencies” in your terminal Gradle Dependency Tree Printed in Console Recently, in one of my projects, we were stuck at a very annoying exception IllegalStateException: WorkManager is already initialized .

March 9, 2020

7 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.

Источник

Оцените статью