Your First Kotlin Android App: An App From Scratch
Part 2: Work with an Android Activity Access Views Using View Binding
— Android & Kotlin

Lesson Complete

Play Next Lesson
Next

Access Views Using View Binding

This video was last updated on Jul 5 2022

Learn to access and interact with the views created in xml from inside your activity using the view binding feature.

Contributors

It’s time to start writing some kotlin code.

You will be doing this inside a class called an “Activity.”

An activity is simply a single screen in an app. So for example the login screen in your app would be one activity.

This activity class is responsible for providing the window in which you can place your UI.

This is achieved with the setContentView(view) function which you’ll be using shorthly. Although the role of an android activity is gradually changing in recent times, for now let’s just say it presents an app screen.

In order to access views from the xml file inside an android activity. You’ll be using a feature called viewBinding.

This generates a class for the xml layout file with a member to represent each view. You’ll learn more about classes in the next episode but for now just see class as a blueprint for something. In this case a blueprint of the view in kotlin code.

Previously, this would be achieved with the findViewById() function. A function in koltin is just simply an action. So the action here is to find a view by it’s id.

But using viewBinding has some advantages.

For instance, you can’t access a view that does not exist because the binding instance creates direct references to the views in the xml file.

Secondly, the view’s data type would always be the correct one because the binding objects always have the same type as the views they reference in the xml layout file.

If you used findViewById() function, you’d have to create each view’s instance manually just like the button example in the slide. And sometimes you might pass the wrong type or try to access a view that doesnt exist.

Some terms might sound strange to you, not to worry, you’ll learn more about classes and functions in the next episode.

Demo 1

To use viewBinding, you have to enable it in the builde.gradle file. Unfold the “Gradle Script” section in the Project panel. Then open up the build.gradle file for the app module you’re working in. Emphasis on the word “app.”

Inside this file, you can see the various configurations for the app. You can see stuffs like the minimum android version this app can work on.

And if you scroll down you can also see dependencies that this app depends on. For instance, the constraint layout dependency. If you remove this, the constraint layout feature will no longer work in our application.

Dependencies are very important in app development because not all features are shipped with Android when you install it on your computer. This is done to make your app size small . Then you can add certain dependencies only when your app needs them.

To use something like Google Map, you’ll have to add and download the dependency.

You get the idea.

Now, back to why you are here. You want to enable viewBinding. For this, scroll up and add the following code in the android block of the build.gradle file:

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

This will enable viewBinding in the application. This means that every layout file will have a binding class generated for it.

To make this work, you have to sync the file so the project can be updated with this feature. Look at the top of the screen, you’ll see a notification telling you that the you need to sync the project. Go ahead and click on “Sync Now”.

This downloads the viewBinding dependency and builds the project with the updated feature.

Now that you have viewBinding setup, you can close this file and open up MainActivity.kt file.

To use viewBinding to access the layout and the views in it, you need to first:

  • Create a variable to store the generated binding class.

Lets do that now. Enter the following code:

private lateinit var binding: ActivityMainBinding

In here, you created a variable called binding that will hold the binding object for the layout file. A variable is just something that holds some data.

This variable has a type of ActivityMainBinding. This means that the data it will store will be an ActivityMainBinding. And notice the naming of this binding class: It is named based on the layout file, in this case activity_main.xml.

By giving this variable a type, it protects the variable from accepting the wrong type. For example, the binding variable cannot store a number or text. By specifying a type, you reduce the chances of getting an error.

As a side note, the lateinit keyword means that you will assign a value to this variable later. As you can see, you have not assigned it to anything yet. You’ll do that now. Update your code to the following:

...
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
...

First you assign the binding variable to ActivityMainBinding.inflate(). The inflate method converts the xml layout file into its corresponding view objects which can be used in your Kotlin code. With this, the binding variable now stores the view of the layout file of the activity.

Next, you access the root view of the layout file using binding.root and then assign it to a variable called view. In this case, the root view would be the ConstraintLayout.

You use val here instead of var because you are not going to be reassigning this variable to something else down the line. So you’re telling kotlin that the value stored here is final.

Finally, you set the content view of this activity to the view varible. This means that this activity will display the constraint layout and all its children like before. But this time around using the view binding feature.

Run the app to try it out. Cool!!! Everything works the same.

Now, the core of developing any android application is for the developer to be able to access the views and programmatically interact with them. For example, say you want to change the target value.

First, you need to access it. For this enter the following code…

After you type binding then press dot, the Intellisence in Android studio kicks in. It shows you the list of properties that the binding object has. You can see all the views you added in the layout file. And they are identified by their id.

Now you can see the benefit of using a meaningful id. you can easily see the targetTextView and know the view its refering to as compared to an id of textView3 or textView4. you can then type in target or select it from the list.

Then set its text to 52 like so:

binding.targetTextView.text = "52"

Then restart the activity. And you can see the UI is updated with the new target value of 52.

Do note that the . operator is used to access the properties of an instance.

And the properties of the views are the same as those in the attributes panel in the layout design view.

Remember, you can set the text in the attributes panel but instead you’re doing it programmatically this time around.

Reviews

Comments