Reader small image

You're reading from  Android Studio 4.2 Development Essentials - Kotlin Edition

Product typeBook
Published inAug 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781803231549
Edition1st Edition
Languages
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

18. An Overview of Android View Binding

An important part of developing Android apps involves the interaction between the code and the views that make up the user interface layouts. This chapter will look at the options available for gaining access to layout views in code with a particular emphasis on an option known as view binding. Once the basics of view bindings have been covered, the chapter will outline the changes necessary to convert the AndroidSample project to use this approach.

18.1 Find View by Id and Synthetic Properties

As outlined in the chapter entitled “The Anatomy of an Android Application”, all of the resources that make up an application are compiled into a class named R. Amongst those resources are those that define layouts. Within the R class is a subclass named layout, which contains the layout resources, including the views that make up the user interface. Most apps will need to implement interaction between the code and these views, for example when reading the value entered into the EditText view or changing the content displayed on a TextView.

Over the years, a number of different approaches to referencing layout views have been introduced. The oldest option involves writing code to manually find a view based on its id via a method named findViewById(). For example:

val myTextView: TextView = findViewById(R.id.myTextView)

With the reference obtained, the properties of the view can then be accessed. For example:

myTextView...

18.2 View Binding

When view binding is enabled in an app module, Android Studio automatically generates a binding class for each layout file within the module. Using this binding class, the layout views can be accessed from within the code without the need to use findViewById() or Kotlin synthetic properties.

The name of the binding class generated by Android Studio is based on the layout file name converted to so-called “camel case” with the word “Binding” appended to the end. In the case of the activity_main.xml file, for example, the binding class will be named ActivityMainBinding.

Android Studio 4.2 is inconsistent in using view bindings within project templates. The Empty Activity template used when we created the AndroidSample project, for example, does not use view bindings. The Basic Activity template, on the other hand, is implemented using view binding. If you use a template that does not use view binding, it is important to know how to...

18.3 Converting the AndroidSample project

The remainder of this chapter we will practice migrating to view bindings by converting the AndroidSample project to use view binding instead of using Kotlin synthetic properties.

Begin by launching Android Studio and opening the AndroidSample project created in the chapter entitled “Creating an Example Android App in Android Studio”.

18.4 Enabling View Binding

To use view binding, some changes must first be made to the build.gradle file for each module in which view binding is needed. In the case of the AndroidSample project, this will require a small change to the Gradle Scripts -> build.gradle (Module: AndroidSample.app) file. Load this file into the editor, locate the android section and add an entry to enable the viewBinding property as follows (note that the kotlin-android-extensions plugin will no longer be needed and may be deleted from the configuration):

plugins {

    id 'com.android.application'

    id 'kotlin-android'

.

.

android {

 

    buildFeatures {

        viewBinding true

    }

.

.

Once this change has been made, click on the Sync Now link at the top of the editor panel, then use the Build menu to clean and then...

18.5 Using View Binding

The first step in this process is to “inflate” the view binding class so that we can access the root view within the layout. This root view will then be used as the content view for the layout.

The logical place to perform these tasks is within the onCreate() method of the activity associated with the layout. A typical onCreate() method will read as follows:

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

}

To switch to using view binding, the view binding class will need to be imported and the class modified as follows. Note that since the layout file is named activity_main.xml, we can surmise that the binding class generated by Android Studio will be named ActivityMainBinding. Note that if you used a domain other than com.example when creating the project, the import statement below will need to be...

18.6 Choosing an Option

Their failure to adopt view bindings in the Empty Activity project template not withstanding, Google strongly recommends the use of view binding wherever possible. In fact, support for synthetic properties is now deprecated and will likely be removed in a future release of Android Studio. When developing your own projects, therefore, view binding should probably be used.

18.7 View Binding in the Book Examples

Any chapters in this book that rely on a project template that does not implement view binding will first be migrated. Instead of replicating the steps every time a migration needs to be performed, however, these chapters will refer you back here to refresh your memory (don’t worry, after a few chapters the necessary changes will become second nature). To help with the process, the following section summarizes the migration steps more concisely.

18.8 Migrating a Project to View Binding

The process for converting a project module to use view binding involves the following steps:

1. Edit the module level Gradle build script file listed in the Project tool window as Gradle Scripts -> build.gradle (Module: <project name>.app) where <project name> is the name of the project (for example AndroidSample).

2. Locate the android section of the file and add an entry to enable the viewBinding property as follows:

android {

 

    buildFeatures {

        viewBinding true

    }

.

.

3. Click on the Sync Now link at the top of the editor to resynchronize the project with these new build settings.

4. Edit the MainActivity.kt file and modify it to read as follows (where <reverse domain> represents the domain name used when the project was created and <project name> is replaced by the lowercase name...

18.9 Summary

Prior to the introduction of Android Studio 3.6, access to layout views from within the code of an app involved the use of either the findViewById() method or Kotlin synthetic properties. An alternative is now available in the form of view bindings. View bindings consist of classes which are automatically generated by Android Studio for each XML layout file. These classes contain bindings to each of the views in the corresponding layout, providing an alternative to synthetic properties, and a safer option to that offered by the findViewById() method. As of Android Studio 4.2, however, view bindings are not enabled by default in some project templates and additional steps are required to manually enable and configure support within each project module.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.2 Development Essentials - Kotlin Edition
Published in: Aug 2021Publisher: PacktISBN-13: 9781803231549
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor's degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth