Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 642
Rama Avatar asked Mar 31 '16 14:03

Rama


2 Answers

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.

like image 51
Lesio Pinheiro Avatar answered Sep 22 '22 06:09

Lesio Pinheiro


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

like image 28
Hemant Parmar Avatar answered Sep 24 '22 06:09

Hemant Parmar