Rama
Rama

Reputation: 429

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

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?

Upvotes: 7

Views: 8805

Answers (2)

Hemant Parmar
Hemant Parmar

Reputation: 3976

For set and get Updated model from your XML. you have to do this in Edittext:

from:

android:text="@{user.name}"

to :

 android:text="@={user.name}"

Happy coding!!

Upvotes: 2

Lesio Pinheiro
Lesio Pinheiro

Reputation: 166

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.

Upvotes: 15

Related Questions