How to use ObservableFields class in Android DataBinding

In this android programming source code example, we are going to use ObservableFields class in Android DataBinding.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to use ObservableFields class in Android DataBinding.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>
        <variable
            name="country"
            type="com.bluapp.androidview2.firebaseMlKitAndDataBinding.FirebaseMlKitAndDataBindingActivity13.CountryObject"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="30dp">

        <TextView
            android:id="@+id/countryName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text='@{country.name}'
            android:gravity="center"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;

import android.os.Bundle;

import com.bluapp.androidview2.databinding.ActivityFirebaseMlKitAndDataBinding13Binding;

public class FirebaseMlKitAndDataBindingActivity13 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebase_ml_kit_and_data_binding13);
        CountryObject country = new CountryObject();
        ActivityFirebaseMlKitAndDataBinding13Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_firebase_ml_kit_and_data_binding13);
        binding.setCountry(country);
        country.name.set("Nigeria, Sweden, India e.t.c");
    }

    public class CountryObject{
        public final ObservableField<String> name = new ObservableField<>();
    }
}

app/build.gradle

dataBinding {
        enabled = true
    }

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment