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

.

.

class MainFragment : Fragment() {

.

.

    override fun onActivityCreated(savedInstanceState: Bundle?) {

        super.onActivityCreated(savedInstanceState)

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

    }

}

Next, edit the MainViewModel.kt file and continue deleting code as follows (note also the conversion of the dollarText variable to LiveData):

package com.ebookfrenzy.viewmodeldemo.ui.main

 

import androidx.lifecycle.ViewModel

import androidx.lifecycle.MutableLiveData

 

class MainViewModel : ViewModel() {

 

    private val rate = 0.74f

    var dollarValue: MutableLiveData<String> = MutableLiveData()

    var result: MutableLiveData<Float> = MutableLiveData()

}

Though we‘ll be adding a few additional lines of code in the course of implementing data binding, clearly data binding has significantly reduced the amount of code that needed to be written.

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 Gradle Scripts -> build.gradle (Module: ViewModelDemo.app) file.

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-kapt'

}

  

android {

  

    buildFeatures {

        viewBinding true

        dataBinding true

    }

.

.

}

Once the entry has been added, a yellow bar will appear across the top of the editor screen containing a Sync Now link. Click this to resynchronize the project with the new build configuration settings.

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"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            tools:context=".ui.main.MainFragment">

.

.

        </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

Once these changes have been made, switch back to Design mode and note that the new root view, though invisible in the layout canvas, is now listed in the component tree as shown in Figure 43-1:

Figure 43-1

Build and run the app to verify that the addition of the layout element has not changed the user interface appearance in any way.

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" />

    </data>

 

    <androidx.constraintlayout.widget.ConstraintLayout

        android:id="@+id/main"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:context=".ui.main.MainFragment">

.

.

</layout>

Build and run the app once again to make sure that these changes take effect.

43.5 Working with the Binding Class

The next step is to modify the code within the MainFragment.kt file to inflate the data binding. This is best achieved by rewriting the onCreateView() method:

.

.

import androidx.databinding.DataBindingUtil

 

import com.ebookfrenzy.viewmodeldemo.R

.

.

class MainFragment : Fragment() {

 

    companion object {

        fun newInstance() = MainFragment()

    }

 

    private lateinit var viewModel: MainViewModel

    lateinit var binding: MainFragmentBinding

 

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

                              savedInstanceState: Bundle?): View {

 

        binding = DataBindingUtil.inflate(

                inflater, R.layout.main_fragment, container, false)

 

        binding.setLifecycleOwner(this)

        return binding.root

    }

.

.

The old code simply inflated the main_fragment.xml layout file (in other words created the layout containing all of the view objects) and returned a reference to the root view (the top level layout container). The Data Binding Library contains a utility class which provides a special inflation method which, in addition to constructing the UI, also initializes and returns an instance of the layout‘s data binding class. The new code calls this method and stores a reference to the binding class instance in a variable:

binding = DataBindingUtil.inflate(

                inflater, R.layout.main_fragment, container, false)

The binding object will only need to remain in memory for as long as the fragment is present. To ensure that the instance is destroyed when the fragment goes away, the current fragment is declared as the lifecycle owner for the binding object.

binding.setLifecycleOwner(this)

return binding.getRoot()

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 using the Build -> Make Project menu option to force the class to be generated. With these changes made, the next step is to begin inserting some binding expressions into the view elements of the data binding layout file.

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="parent" />

The expression begins by checking if the result value is currently zero and, if it is, displays a message instructing the user to enter a value. If the result is not zero, however, the value is converted to a string and concatenated with the word “euros” before being displayed to the user.

The result value only requires a one-way binding in that the layout does not ever need to update the value stored in the ViewModel. The dollarValue EditText view, on the other hand, needs to use two-way binding so that the data model can be updated with the latest value entered by the user, and to allow the current value to be redisplayed in the view in the event of a lifecycle event such as that triggered by a device rotation. The dollarText element should now be declared as follows:

<EditText

    android:id="@+id/dollarText"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginTop="96dp"

    android:ems="10"

    android:importantForAutofill="no"

    android:inputType="numberDecimal"

    android:text="@={myViewModel.dollarValue}"

    app:layout_constraintEnd_toEndOf="parent"

    app:layout_constraintHorizontal_bias="0.502"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toTopOf="parent" />

Now that these initial binding expressions have been added a method now needs to be written to perform the conversion when the user clicks on the Button widget.

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 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(rate)

            } else {

                result.value = 0f

            }

        }

    }

}

Note that in the absence of a valid dollar value, a zero value is assigned to the result LiveData variable. This ensures that the binding expression assigned to the resultText TextView displays the “Enter value” message if no value has been entered by the user.

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="@+id/resultText" />

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.

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

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