That question has certainly outlived its time in android development. With Kotlin synthetics deprecated now is also gaining popularity. Ever since Data Bindings introduction developers were very happy about it and some developers like me were a little bit confused with questions like.
- What is the difference between View Binding and Data Binding?
- What should I use for my project?
- Which one is better Android View Binding or Data Binding?
so I am going to try to answer most of these questions along with a use case for both of them. But (there’s always one isn’t it) if you expect an answer to what you should use please be very informed that I will try to answer that but based on a few situations and these answers will be completely opinionated.
Table of Contents
- 1 What are View Binding and Data Binding?
- 2 How to Implement? (Use cases one each)
- 3 Creating Layouts
- 4 Changes Needed in Layout Files
- 5 Code for the first activity (DataEntryActivity)
- 6 Code for the second activity (MainActivity)
- 7 Whats Next?
- 8 What to use View Binding or Data Binding? (Opinionated)
- 9 Conclusion
What are View Binding and Data Binding?
Other than being a part of Android Jetpack and being an awesome help to developers. These both have almost similar functions so they need explanation before understanding what exactly to use
View Binding
You might be aware of what view binding is but for the sake of simplicity. It is used to make working with views extremely easy and reduces a lot of boilerplate code which makes it very easy to work with views and makes it simpler to perform operations on them
How it works is very simple when view binding is enabled in an android project module. It automatically generates a binding class for the layout file which contains direct reference to those views and by the id that is given to them in the XML layout. Which later can be used instead of creating a variable for it ourselves and then casting it using findViewById
Benefits:
- Speed Increase -> No more findViewById code and no need to worry if you remove a view errors will start showing right away
- Code Readability -> Code readability is highly increased if you give sensible ids to the views
- Reduces Crashes -> This is achieved by type safety if you are never going to define what a view is to be cast as you can not make a mistake
Data Binding
Data binding in very simple words can be considered as something that does the same as view binding but adds a little more to it and reduces work we have to do even more. As the name suggests we have to bind the data to the views and that is what exactly happens. A data source is specified in the XML file and when the view is displayed an instance of the data is also passed which can be used to set attributes automatically.
If this seems confusing don’t worry you are not alone it will be explained in the use case example.
Benefits:
- Everything that is in View Binding
- Complexity Reduction-> Data Binding could be not so straight to start with but once you get a hang of it will boost your development speed
- Reduces Code-> The ease of letting go of updating a view multiple times can easily reduce many lines of code
How to Implement? (Use cases one each)
It is always easier to learn while doing so for this case we take an example of an app that has 2 screens as given below they both are very simple and their layout files are given below
Both of These are extremely easy to implement and take virtually no work. All you need to do is to add a couple of lines to your app level gradle file or better said as module level gradle files in whatever modules you want to use them
in case of View binding just add this to your app (module) level gradle file
1 2 3 4 5 6 7 |
android { buildFeatures { viewBinding true } } |
in case of Data binding just add this to your app (module) level gradle file
1 2 3 4 5 6 7 |
android { buildFeatures { dataBinding true } } |
also add a plugin in the same file for Data Binding
1 2 3 |
apply plugin: "kotlin-kapt" |
this is how you activate these in your app(module) level gradle for your app
Creating Layouts
So we create 2 activities as given below
Our launcher activity is going to be DataEntryActivity not MainActivity
For activity_data_entry.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DataEntryActivity"> <EditText android:id="@+id/firstName_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:hint="First Name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/lastName_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:hint="Last Name" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/firstName_et" /> <Button android:id="@+id/go_ahead_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GO AHEAD" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/lastName_et" /> </androidx.constraintlayout.widget.ConstraintLayout> |
For activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/firstNameTv" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="24dp" android:layout_marginEnd="16dp" android:textAlignment="center" android:textSize="20sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:text="First Name" /> <TextView android:id="@+id/lastNameTv" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="24dp" android:layout_marginEnd="16dp" android:textAlignment="center" android:textSize="20sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/firstNameTv" tools:text="Last Name" /> <Button android:id="@+id/back_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Back" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/lastNameTv" /> </androidx.constraintlayout.widget.ConstraintLayout> |
Changes Needed in Layout Files
There is absolutely no change required in View Binding layouts the binding classes are automatically generated for each file you have in your layouts resource folder
But for Data Binding these changes need to be done for every layout you want to get a binding class generated for here are the changes you need to perform in XML resource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <!--Add this layout tag as parent to the layout--> <!--can be easily done using alt+enter when cursor is in root element and is text focused there--> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <!--usage will be explained later --> <data></data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> </androidx.constraintlayout.widget.ConstraintLayout> </layout> |
This is necessary to get the binding file generated from the Android Studio
Note: Please rebuild or make your project again to get the binding classes generated
Code for the first activity (DataEntryActivity)
Mostly we are supposed to add more things so that we can worry about other things that may affect our apps in different situations but for the sake of simplicity we are going to skip that
View Binding
In the case of view binding work is very simple all you need to do is add this code to your onCreate function in Activity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class DataEntryActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Here we use generated class for binding to inflate the layout and then pass it to set as the view val binding = ActivityDataEntryBinding.inflate(layoutInflater) setContentView(binding.root) //We use a scope function so that we don't have to write binding again and again binding.apply { //Set a listener on GO AHEAD button goAheadBtn.setOnClickListener { //Getting the text in fields val firstName = firstNameEt.text.toString() val lastName = lastNameEt.text.toString() //Creating an intent and starting an activity by passing the text in input fields val intent = Intent(this@DataEntryActivity, MainActivity::class.java) intent.putExtra("first",firstName) intent.putExtra("last",lastName) startActivity(intent) } } } } |
Data Binding
Because what we want to implement is really the same thing we keep the logic just the same
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class DataEntryActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Here we set the view and then cast the instance we get via DataBindingUtil as the generated class val binding: ActivityDataEntryBinding = DataBindingUtil.setContentView(this, R.layout.activity_data_entry) //We use a scope function so that we don't have to write binding again and again binding.apply { //Set a listener on GO AHEAD button goAheadBtn.setOnClickListener { //Getting the text in fields val firstName = firstNameEt.text.toString() val lastName = lastNameEt.text.toString() //Creating an intent and starting an activity by passing the text in input fields val intent = Intent(this@DataEntryActivity, MainActivity::class.java) intent.putExtra("first",firstName) intent.putExtra("last",lastName) startActivity(intent) } } } } |
Note: This could also be done in other and comparatively easier way but for the sake of simplicity we believe this approach would be better
Code for the second activity (MainActivity)
View Binding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Here we use generated class for binding to inflate the layout and then pass it to set as the view val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // Here we get the data sent in the previous activity //And check if it is null and replace with empty string if it is val firstName = intent.getStringExtra("first")?:"" val lastName = intent.getStringExtra("last")?:"" //Using a scope function to avoid writing binding again and again binding.apply { //Setting Name on the textViews firstNameTv.text = firstName lastNameTv.text = lastName //BackBtn click is set to finish this activity backBtn.setOnClickListener { finish() } } } } |
now that is all you need to do in view binding and the functionality of app is achieved
Data Binding
We could do the same in data binding if we want but we are going to do it a little bit differently and this is where the main difference is
for this one we quickly create a whole new data class like this
1 2 3 4 5 6 |
data class Name( val firstName: String, val lastName: String ) |
and then quickly define a variable in layout file like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="name" type="com.simplifiedcoding.bindingexample.Name" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/firstNameTv" ... android:text="@{name.firstName}" /> <TextView android:id="@+id/lastNameTv" ... android:text="@{name.lastName}" /> <Button android:id="@+id/back_btn" ... /> </androidx.constraintlayout.widget.ConstraintLayout> </layout> |
So now to explain what we did here we defined a variable in the XML resource so that when a Binding file is created we have a variable pre-defined in it and now when the variable change the fields that are associated with it also change in this example it would be the text fields in lastNameTv & firstNameTv
and now for the MainActivity.kt file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Here we set the view and then cast the instance we get via DataBindingUtil as the generated class val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) // Here we get the data sent in the previous activity //And check if it is null and replace with empty string if it is val firstName = intent.getStringExtra("first")?: "" val lastName = intent.getStringExtra("last")?: "" //Using a scope function to avoid writing binding again and again binding.apply { //Setting the value we got into a variable of layout name = Name(firstName,lastName) backBtn.setOnClickListener { finish() } } } } |
And here we use that name variable to be set as the values sent via other activity what this will do is it will set the values associated with the variable in the view automatically
in this example it may seem of no point but in a bigger project it would completely change how much extra code you have to write
Whats Next?
For the purpose of this app this is it we have implemented the functionality pretty easily and have got nothing much to worry about
In the case of View Binding this is almost it there is nothing really magical we could do with it and thus implementing View Binding is also very light in terms of Apk size
But in case of data binding there are many features we haven’t gotten into and while it is a bit heavier than view binding (Just in some KB) it makes up for it in the amount of ease and simplicity it provides.
There are a lot of things you can do with data binding other than setting the views automatically for example it is truly an ease to just use it directly to observe a view model from it and you could also go into binding adapters which make writing a bunch of repeated code in the app pretty easy. But that is a tutorial for another day.
What to use View Binding or Data Binding? (Opinionated)
If we look at the question we started “View Binding or Data Binding” as most will say and is the better answer to the question is that it really depends on your usage
but if you would have to ask me to choose one for you consider following situations. For a smaller project with supposedly like 2-3 screens use of View Binding should be able to suffice your need while keeping the project clean and clear also if you are a beginner use View Binding to get started and later go to Data Binding for a project that is bigger than that such as 4-5 screens or more go with Data Binding because this will really cut down on the complexity and development time for the project
Conclusion
It is clear and evident that both of these have same benefits with Data Binding having more of weight age regarding benefits. So that is all for this question of “View Binding or Data Binding“. I hope I taught you something new with this post. And if you think it is really useful then please support me by sharing this post with your friends. Thank You.