How to update an object from the UI with Android Data Binding?

Rama picture Rama · Mar 31, 2016 · Viewed 7.8k times · Source

I am using Data Binding and I've created a very simple class

public class ViewUser extends BaseObservable {
    private String name;

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }
}

with a simple layout

<?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="user"
            type="com.example.ViewUser" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="top"
                    android:lines="3"
                    android:text="@{user.name}" />
    </LinearLayout>
</layout>

When I update the object, the UI updates without any problem, but if I change the value of the EditText from the UI and then get the user using the DataBindingUtil .getUser(), it doesn't have the updated value. Is it possible to have the property updated automatically or do I have to update the object using some event like TextWatcher's onTextChanged?

Answer

Lesio Pinheiro picture Lesio Pinheiro · Oct 7, 2017

Your xml tag android:text is missing a =, after the @: android:text="@={user.name}"

The @={} means "two way data binding". The @{} is one way data binding.