Changes

An Android Jetpack Data Binding Tutorial

358 bytes removed, 18:43, 16 January 2019
Adding Binding Expressions
== Adding 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 Text mode and make these changes:
 
        <android.support.constraint.ConstraintLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/main"
            android:layout_width="match_parent"
Build and run the app once again to make sure that these changes take effect.
== Working Working with the Binding Class ==
The next step is to modify the code within the MainFragment.java file to obtain a reference to the binding class instance. This is best achieved by rewriting the onCreateView() method:
 
        return binding.getRoot();
        return inflater.inflate(R.layout.main_fragment, container, false);
    }
.
With these changes made, the next step is to begin inserting some binding expressions into the view elements of the data binding layout file.
== Adding 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:
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="MainFragment"
    android:text='@{safeUnbox(myViewModel.result) == 0.0 ? "Enter value" : String.valueOf(safeUnbox(myViewModel.result)) + " euros"}'
    app:layout_constraintBottom_toBottomOf="parent"