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

2

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?

Apollonian answered 31/3, 2016 at 14:59 Comment(4)
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).Repugn
This might help: #33363033Occurrence
Two-way data binding has been added to Android Studio 2.1 preview. Take a look at this blog: halfthought.wordpress.com/2016/03/23/…Monoplegia
How do you access the updated model in your activity. Would have loved to see your activity.Punch
A
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.

Argentite answered 6/10, 2017 at 23:35 Comment(0)
O
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!!

Onetime answered 8/11, 2017 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.