Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Kotlin Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815987
Edition1st Edition
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

43. An Android Jetpack Data Binding Tutorial

So far in this book we have covered the basic concepts of modern Android app architecture and looked in more detail at the ViewModel and LiveData components. The concept of data binding was also covered in the previous chapter and will now be used in this chapter to further modify the ViewModelDemo app.

43.1 Removing the Redundant Code

If you have not already done so, copy the ViewModelDemo project folder and save it as ViewModelDemo_LiveData so that it can be used again in the next chapter. Once copied, open the original ViewModelDemo project ready to implement data binding.

Before implementing data binding within the ViewModelDemo app, the power of data binding will be demonstrated by deleting all of the code within the project that will no longer be needed by the end of this chapter.

Launch Android Studio, open the ViewModelDemo project, edit the MainFragment.kt file and modify the code as follows:

package com.ebookfrenzy.viewmodeldemo.ui.main

 

import androidx.lifecycle.ViewModelProvider

import android.os.Bundle

import android.support.v4.app.Fragment

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import com.ebookfrenzy.viewmodeldemo.R

 

class MainFragment : Fragment() {

.

.

&...

43.2 Enabling Data Binding

The first step in using data binding is to enable it within the Android Studio project. This involves adding a new property to the Module level build.gradle file, so open this file (app -> Gradle Scripts -> build.gradle (Module: ViewModelDemo.app)) as highlighted in Figure 43-1:

Figure 43-1

Within the build.gradle file, add the element shown below to enable data binding within the project and to apply the Kotlin kapt plugin. This plugin is required to process the data binding annotations that will be added to the fragment XML layout file later in the chapter:

plugins {

    id 'com.android.application'

    id 'kotlin-android'

    id 'kotlin-android-extensions'

    id 'kotlin-kapt'

}

  

android {

  

    buildFeatures {

      ...

43.3 Adding the Layout Element

As described in “An Overview of Android Jetpack Data Binding”, in order to be able to use data binding, the layout hierarchy must have a layout component as the root view. This requires that the following changes be made to the main_fragment.xml layout file (app -> res -> layout -> main_fragment.xml). Open this file in the layout editor tool, switch to Code mode and make these changes:

<?xml version="1.0" encoding="utf-8"?>

 

<layout xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:android="http://schemas.android.com/apk/res/android">

 

        <androidx.constraintlayout.widget.ConstraintLayout

            android:id="@+id/main...

43.4 Adding the Data Element to Layout File

The next step in converting the layout file to a data binding layout file is to add the data element. For this example, the layout will be bound to MainViewModel so edit the main_fragment.xml file to add the data element as follows:

<?xml version="1.0" encoding="utf-8"?>

 

<layout xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:android="http://schemas.android.com/apk/res/android">

 

    <data>

        <variable

            name="myViewModel"

            type="com.ebookfrenzy.viewmodeldemo.ui.main.MainViewModel" />

  ...

43.5 Working with the Binding Class

The next step is to modify the code within the MainFragment.kt file to obtain a reference to the binding class instance. This is best achieved by rewriting the onCreateView() method:

.

.

import androidx.databinding.DataBindingUtil

import com.ebookfrenzy.viewmodeldemo.databinding.MainFragmentBinding

.

.

class MainFragment : Fragment() {

 

    companion object {

        fun newInstance() = MainFragment()

    }

 

    private lateinit var viewModel: MainViewModel

    lateinit var binding: MainFragmentBinding

 

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,

                           ...

43.6 Assigning the ViewModel Instance to the Data Binding Variable

At this point, the data binding knows that it will be binding to an instance of a class of type MainViewModel but has not yet been connected to an actual MainViewModel object. This requires the additional step of assigning the MainViewModel instance used within the app to the viewModel variable declared in the layout file. Since the reference to the ViewModel is obtained in the onActivityCreated() method, it makes sense to make the assignment there:

.

.

import com.ebookfrenzy.viewmodeldemo.BR.myViewModel

.

.

override fun onActivityCreated(savedInstanceState: Bundle?) {

    super.onActivityCreated(savedInstanceState)

    viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

 

    binding.setVariable(myViewModel, viewModel)

}

.

.

If Android Studio reports myViewModel as undefined, rebuild the project...

43.7 Adding Binding Expressions

The first binding expression will bind the resultText TextView to the result value within the model view. Edit the main_fragment.xml file, locate the resultText element and modify the text property so that the element reads as follows:

<TextView

    android:id="@+id/resultText"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text='@{safeUnbox(myViewModel.result) == 0.0 ? "Enter value" : String.valueOf(safeUnbox(myViewModel.result)) + " euros"}'

    app:layout_constraintBottom_toBottomOf="parent"

    app:layout_constraintEnd_toEndOf="parent"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toTopOf="...

43.8 Adding the Conversion Method

When the Convert button is clicked, it is going to call a method on the ViewModel to perform the conversion calculation and place the euro value in the result LiveData variable. Add this method now within the MainViewModel.kt file:

.

.

class MainViewModel : ViewModel() {

 

    private val usd_to_eu_rate = 0.74f

    public var dollarValue: MutableLiveData<String> = MutableLiveData()

    public var result: MutableLiveData<Float> = MutableLiveData()

 

    fun convertValue() {

        dollarValue.let {

            if (!it.value.equals("")) {

                result.value = it.value?.toFloat()?.times(usd_to_eu_rate)

  ...

43.9 Adding a Listener Binding

The final step before testing the project is to add a listener binding expression to the Button element within the layout file to call the convertValue() method when the button is clicked. Edit the main_fragment.xml file in Code mode once again, locate the convertButton element and add an onClick entry as follows:

<Button

    android:id="@+id/convertButton"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginTop="77dp"

    android:onClick="@{() -> myViewModel.convertValue()}"

    android:text="Convert"

    app:layout_constraintEnd_toEndOf="parent"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toBottomOf...

43.10 Testing the App

Compile and run the app and test that entering a value into the dollar field and clicking on the Convert button displays the correct result on the TextView (together with the “euros” suffix) and that the “Enter value” prompt appears if a conversion is attempted while the dollar field is empty. Also, verify that information displayed in the user interface is retained through a device rotation.

43.11 Summary

The primary goal of this chapter has been to work through the steps involved in setting up a project to use data binding and to demonstrate the use of one-way, two-way and listener binding expressions. The chapter also provided a practical example of how much code writing is saved by using data binding in conjunction with LiveData to connect the user interface views with the back-end data and logic of the app.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Kotlin Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815987
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