7

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?

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Rama
  • 429
  • 1
  • 8
  • 14
  • 1
    AFAIK, you have to handle this yourself. For example, in this case, if data binding did what you want, you are at risk of an infinite loop (`EditText` calls `setUser()` which says the model changed which causes data binding to update the `EditText` which calls `setUser()` which...). Also bear in mind that what you want would need to be opt-in, as not everyone wants their model updated on a per-keystroke basis (as you imply with `TextWatcher`). – CommonsWare Mar 31 '16 at 15:03
  • This might help: http://stackoverflow.com/questions/33362533/create-two-way-binding-with-android-data-binding – fweigl Mar 31 '16 at 15:08
  • How do you access the updated model in your activity. Would have loved to see your activity. – Parag Kadam Apr 16 '17 at 09:32
  • 1
    Two-way data binding has been added to Android Studio 2.1 preview. Take a look at this blog: https://halfthought.wordpress.com/2016/03/23/2-way-data-binding-on-android/ – George Mount Apr 04 '16 at 17:28

2 Answers2

15

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.

Lesio Pinheiro
  • 166
  • 2
  • 4
2

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!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49