Hey Techoz, Hope you are rocking with your computers in the digital world! Well, today we will be discussing about one of the most interesting topic which is view Binding in android app tutorial.
Why use View Binding in our android application?
View Binding library:
- Eliminates redundant calls to
findViewById()
method - Reduces boilerplate code
- Makes code more readable
- Avoids the chances of Null reference exceptions
These above points help us to understand how much benefit we can achieve by using view binding library in our android app. Again, while we start working on this view binding in android tutorial, things will get more clear.
Before moving to the implementation, have a look at what we are going to build.
If you would prefer video tutorial, then you can watch the below video for View Binding in Android Tutorial:
Initial setup
To use View Binding in android app, we don’t need much complicated setup. Just go to your module-level build.gradle
file and inside the android tag, paste the following code as follows:
android {
...
...
buildFeatures {
viewBinding true
}
...
}
After this, sync the project, the syncing time will take as per the project size. During this time, the compiler will create separate java file for each of the layout files we have in the project. For this view binding in android tutorial project, it will create binding file for activity_main.xml
file.
The View Binding in android follows some naming conventions while creating auto-generated files. It follows the camel case pattern for the layout file name and then suffixed by ‘Binding’ keyword. For ouractivity_main.xml
, it will createActivityMainBinding.java
file.
Now, what’s inside the Binding file?
The auto-generated binding file contains the references for all the views inside each layout file. For ex. in our layout file, we have a button with an id as ‘btn_submit’, then it will be referenced in the binding file as ‘btnSubmit’, and that’s how we can refer them from our code.
Build the layout
Let’s build the view in activity_main.xml
file with the following code.
<?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"
android:layout_margin="8dp">
<EditText
android:id="@+id/enter_text_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter the text here..."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title" />
<Button
android:id="@+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Submit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/enter_text_field" />
<TextView
android:id="@+id/show_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Entered text appears here..."
app:layout_constraintTop_toBottomOf="@+id/submit_button"
android:layout_marginTop="8dp"
android:textSize="20sp"/>
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Technopoints View Binding Tutorial"
app:layout_constraintTop_toTopOf="parent"
android:textSize="30sp"
android:gravity="center_horizontal"
android:textStyle="bold"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The above layout will build the UI as shown above. We don’t have to do anything special in the layout file for view binding.
Implement View Binding in android app
Now go to ActivityMain.kt
file and use the following code inside it.
package com.example.viewbindingtutorial
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.viewbindingtutorial.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.submitButton.setOnClickListener {
binding.showText.text = binding.enterTextField.text
}
}
}
Wondering what the code is? Don’t worry dude, I am here to explain! 😄
Here at first we are declaring a variable binding
as type of ActivityMainBinding
. Android studio will give you this name in the suggestions list because though we haven’t created this class, android studio automatically created this class for us. And then we are initializing the binding with the static method inflate()
inside the binding class and pass the layout inflater as a parameter. Now, we can use this binding variable to reference all the views which are in the layout file.
In the setContentView method, we generally see our layout file is passed as a parameter. But in case of View Binding, we pass it in another way like shown in the above code. Actually, the binding.root
itself returns the layout xml file associated with that binding class. (You can try ctrl + clicking on the root and see it navigates to activity_main.xml
)
Lastly, we are using the binding to call setOnClickListener
on the submit button and inside it, assigning the value in the EditText
to the TextView
. Now try running the app. The app is simple but the change is in logic we are implementing in this view binding in android tutorial.
The view binding library in android is powerful due to some of the great features it provides like it eliminates the need for calling findViewById() method every time the view needs to be referenced. Also, it prevents us to call null references which avoids NullReferenceException.
That’s all friends, about view binding in android app. If you have any doubts in the above implementation, feel free to ask in the comments section below. I will try my best to answer those. If you want want to jump directly to the implementation, feel free to directly download the source code from the github link below.
Download Source Code
Something extra from me… ☺️
I would like to offer something extra from my side. Would you like to take it? If yes, then here it is. Technopoints has started its official WhatsApp Group where programming enthusiasts interact with each others, solve doubts, and learn together. There you will be in a group of like-minded people who are eager to learn, share knowledge, ask doubts and solve others doubts too. Additionally, there I share some of the rare programming tips related to Android development, the solution to the challenges I faced while making app projects which look my lot of time and I got stuck on it. With those tips, you will avoid common mistakes and conquer the hurdles of your programming journey.
Agree? Great! here is the invite link:
Click here to join the Technopoints WhatsApp Group!
It is open for programmers all over the Globe. Lets connect, share knowledge and grow together. See you in the next tutorial soon with another new hot topic. Thanks, Good bye! 😄