View Binding using Activity

ACE
Kotlin Mumbai
Published in
5 min readMar 22, 2020

--

As I’ve seen many programmers not using the latest features provided by the Google into their programming practices or while building up their projects, this is because of some reasons which are likely to be difficult learning curve, less amount of time, confusion in “from where to start?”, laziness, etc.

So, I’ve came to the conclusion, to make a reduction in such thoughts and behavior, I should introduce some notes which is easy to learn and understand all these things in a scattered manner.

A complete programmer is a myth. But, one must always keep in believing to be one. — As this will keep those, in a race with themselves.

Let’s begin with our stuff…!

As the topic highlights itself as View Binding, the questions which comes to the mind are:

  • What is a View Binding?
  • Where & when should we use it?
  • Is it going to do any profit to me? If yes, then as in what?
  • Is it easy to learn?

So, let me answer to all those questions at once over here:

  • View binding is a feature that allows you to write code which interacts with the views more easily.
  • We just need to enable the View Binding into our build.gradle file, starting from now. It doesn’t matter whether your project is big or small, just begin with it and you will come to know its advantages.
  • Yes. It will profit every programmer by reducing those boilerplate codes and saving their precious time.
  • Indeed it is.

Moving further, let’s discuss in detail about the View Binding.

As I’ve mentioned earlier, that View Binding is a feature that allows you to write code which interacts with the views more easily by enabling the view binding in that particular module and then it immediately generates a binding class for each and every XML layout file present in that module which results in replacing findViewById().

Setting up the environment

There are only 3easy steps which needs to be done.

Step 1: Enable view binding by adding the below code to the module level app’s build.gradle file .

android{
...

//Step One
viewBinding {
enabled = true
}
}

Step 2: Add the below provided dependency into the module level app’s build.gradle file to activate the android’s lifecycle.

dependencies {
def
lifecycle_version = '2.2.0'

...

//Step Two
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
}

Note: If you are using the support libraries for building your projects, then I would highly recommend you all the shift to the Androidx.

Or for the ktx version of dependency, you can use the below dependency.

dependencies {
def
lifecycle_version = '2.2.0'

...

//Step Two
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
}

Note: Every ktx version of dependency holds a keyword “-ktx” appended as suffix to their names.

Step 3: Add the below code to the project level build.gradle file.

repositories {
//Step Three
google()
jcenter()

}

Note: As in our latest android studio, the google repository is provided by default. But, still in case of absence of this repository, add this as a step 3.

After completing all these 3 steps, view binding will get enabled for that particular module of the project and thus will generate an instance of each and every view of the every layout file.

After getting our setup done, let’s get started with the real thing. Now, the next thing we need to do is, create a UI for our application. In this UI, we will add a single image, some texts and a button. Then we will bind our views using the view binding method.

Create some views into your activity_mail.xml file.

  • One ImageView as profile picture.
  • Four TextViews as first name, last name, email id and mobile number.
  • And lastly, a button to show a toast on its click.
<?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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity"
>

<ImageView
android:id="@+id/imageViewProfilePic"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="32dp"
android:src="@drawable/ic_launcher_background"
app:layout_constraintDimensionRatio="4:2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<TextView
android:id="@+id/textViewFirstName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:hint="@string/text_hint_first_name"
android:textAppearance="@android:style/TextAppearance.Medium"
app:layout_constraintEnd_toStartOf="@+id/textViewLastName"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageViewProfilePic"
/>

<TextView
android:id="@+id/textViewLastName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:hint="@string/text_hint_last_name"
android:textAppearance="@android:style/TextAppearance.Medium"
app:layout_constraintBaseline_toBaselineOf="@+id/textViewFirstName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/textViewFirstName"
/>

<TextView
android:id="@+id/textViewEmailId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="@string/text_hint_email_id"
android:textAppearance="@android:style/TextAppearance.Medium"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewFirstName"
/>

<TextView
android:id="@+id/textViewMobileNo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="@string/text_hint_mobile_number"
android:textAppearance="@android:style/TextAppearance.Medium"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewEmailId"
/>

<Button
android:id="@+id/buttonNextScreen"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:text="@string/text_label_click"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

Then, we will go for our MainActivity.kt file. And in that will begin by binding our layout file into it.

Step 1: Declare a variable for the layout’s binding class file.

Step 2: Call the ActivityMainBinding class with an extension of .inflate() and the load the layoutInflater in it. Pass that data into the variable which was declared globally.

Step 3: Then, just replace the R.layout.main_activity code with the mActivityMainBinding.root into the setContentView().

By doing all these steps, we load our xml layout file into the setContentView(), similarly as the R.layout.main_activity but by using the view binding method.

class MainActivity : AppCompatActivity() {

private lateinit var mActivityMainBinding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mActivityMainBinding.root)
}
}

Note: The name of the binding class is generated by converting the name of the XML file to camel case and adding the word “Binding” to the end. And if you don’t see any, then just rebuild your project once to make it available for you.

Then similarly, for loading the data into the views, we will create a model class with the name MainViewModel.kt and add the code given below.

class MainViewModel {
val mFirstName: String = "Akshay"
val mLastName
: String = "Sawant"
val mEmailId
: String = "akshaysawant003@gmail.com"
val mMobileNumber
: String = "1234567890"
}

Next, just globally declare this class into your MainActivity.kt file and initialize it into your onCreate() like this below.

class MainActivity : AppCompatActivity() {

//Declare globally
private lateinit var mMainViewModel: MainViewModel

override fun onCreate(savedInstanceState: Bundle?) {
//....

mMainViewModel = MainViewModel()
}
}

Then for loading an image into your ImageView view, add a Glide’s dependency into your module level build.gradle file and sync it.

dependencies {
...
def
glide_version = '4.11.0'

//Glide dependency
implementation "com.github.bumptech.glide:glide:$glide_version"
}

To fetch the data from the view model class and load it into the views, we will do something like this below:

  • We initialize the glide and load our preferred image into it, by setting an error image if anything goes wrong (i.e. if the image doesn’t loads) and finally we mention that view in which we want to load the data into.
  • Call each views id by using the view model’s varible and setting the text into it which we have statically loaded in our MainViewModel.kt class.
  • Similarly, we bind our button with the setOnClickListener() to show a toast message on its click.
Glide.with(this@MainActivity)
.load(R.drawable.ic_people)
.error(R.drawable.ic_launcher_foreground)
.into(mActivityMainBinding.imageViewProfilePic)

mActivityMainBinding.textViewFirstName.text = mMainViewModel.mFirstName
mActivityMainBinding
.textViewLastName.text = mMainViewModel.mLastName
mActivityMainBinding
.textViewEmailId.text = mMainViewModel.mEmailId
mActivityMainBinding
.textViewMobileNo.text = mMainViewModel.mMobileNumber

mActivityMainBinding
.buttonNextScreen.setOnClickListener {
Toast.makeText(this@MainActivity, "Clicked..!", Toast.LENGTH_SHORT).show()
}

Finally, you can connect your device or load an emulator to run our first project on View Binding.

For the source code of this project, you can visit to my github account from the link below:

Do contribute if you think there is need for any betterment or issue into the code and do provide a response below in the comment section, as I would like to improve myself further. Thank you in advance. Happy coding!

--

--

ACE
Kotlin Mumbai

Android Developer | Tech Conference Speaker | Tech Writer @KotlinMumbai @NerdForTech