11. 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 introduced with Android Studio 3.6 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.

11.1 Find View by ID

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.

Prior to the introduction of Android Studio 3.6, the only option for gaining access to a view from within the app code involved writing code to manually find a view based on its id via a method named findViewById(). For example:

TextView exampleView = findViewById(R.id.exampleView);

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

exampleView.setText("Hello");

While finding views by id is still a viable option, it has some limitations, the biggest disadvantage of findViewById() being that it is possible to obtain a reference to a view that has not yet been created within the layout, leading to a null pointer exception when an attempt is made to access the view’s properties.

Since Android Studio 3.6, an alternative way of accessing views from the app code has been available in the form of view bindings.

11.2 View Bindings

When view bindings are 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().

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.

The process for using view bindings within a project module can be summarized as follows:

1. Enable view binding for any project modules where support is required.

2. Edit code to import the auto-generated view binding class.

3. Inflate the binding class to obtain a reference to the binding.

4. Access the root view within the binding and use it to specify the content view of the user interface.

5. Access views by name as properties of the binding object.

11.3 Converting the AndroidSample Project

The remainder of this chapter will demonstrate the use of view bindings by converting the AndroidSample project to use view bindings instead of using findViewById().

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

11.4 Enabling View Binding

As of Android Studio 4.0, view binding is not enabled by default. To use view binding, therefore, some changes must 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 changes to the Gradle Scripts -> build.gradle (Module: AndroidSample.app) file. To begin with, the viewBinding property must be enabled within the android section of the file:

.

.

android {

 

    buildFeatures {

        viewBinding = true

    }

.

.

Once these changes have been made, use the Build menu to clean and then rebuild the project to make sure the binding class is generated. The next step is to use the binding class within the code.

11.5 Using View Bindings

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

protected void onCreate(Bundle savedInstanceState) {

    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 changed to reflect this:

.

. 

import com.ebookfrenzy.androidsample.databinding.ActivityMainBinding;

.

.

public class MainActivity extends AppCompatActivity {

 

    private ActivityMainBinding binding;

.

.

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    binding = ActivityMainBinding.inflate(getLayoutInflater());

    View view = binding.getRoot();

    setContentView(view);

}

Now that we have a reference to the binding we can access the views by name as follows:

public void convertCurrency(View view) {

 

    if (!binding.dollarText.getText().toString().equals("")) {

 

        Float dollarValue = Float.valueOf(binding.dollarText.getText().toString());

        Float euroValue = dollarValue * 0.85F;

        binding.textView.setText(euroValue.toString());

    } else {

        binding.textView.setText(R.string.no_value_string);

    }

}

Compile and run the app and verify that the currency conversion process still works as before.

11.6 Choosing an Option

The introduction of view binding does not invalidate the previous options and both will continue to be widely supported for the foreseeable future. In terms of avoiding null pointer exceptions, however, view bindings are clearly the safer option when compared to using the findViewById() method. When developing your own projects, therefore, view binding should probably be used.

With regards to the examples in this book, however, it is important to keep in mind that view bindings are not enabled by default in Android Studio 4.1. Unfortunately, to use view bindings in the book examples it would be necessary to manually repeat each of the build.gradle and onCreate() method changes in this chapter over 50 times. For this reason alone, the examples in this book continue to use findViewById().

That being said, there is no reason why you should not follow the steps in this chapter to adapt the examples in this book to use view bindings if you wish to do so. In fact, we would encourage you to convert at least a few of the tutorials in the book to use view binding as an exercise to gain familiarity with the concepts.

11.7 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 the findViewById() method. 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 a safer option to that offered by the findViewById() method. As of Android Studio 3.6, however, view bindings are not enabled by default and additional steps are required to manually enable and configure support within each project module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.92