Two Way DataBinding in Java (Programmatically)

2k views Asked by At

The following code is defining user.firstName to EditText by two-way binding approach.

<EditText android:text="@={user.firstName}" .../>

Is there anyway how to set user.firstName to EditText in Java Code programmatically by two way binding approach.

For example;

editText.setTextbyTwoWay(user.fisrtName);

P.S: I forgot to describe the EditText is created programmatically in Java Code. That's why I have to define Text value to this EditText in Java Code for two-way binding.

1

There are 1 answers

0
tynn On

You could do this within the Observable.OnPropertyChangedCallback.onPropertyChanged() and TextWatcher.afterTextChanged() callbacks. But this is a quite extensive implementation and does exactly what would be done within the data bindings.

So you should consider to still use data bindings for the view you define programmatically. Define as much as possible in layout and then inflate it with data bindings. Further customization can be done on the inflated view.

<layout xmlns:android="http://schemas.android.com/apk/res/android>
    <data>
        <variable name="user" type="my.User" />
    </data>
    <EditText
        android:id="@+id/edit_text"
        android:text="@={user.firstName}"
        [...] />
</layout>

Now you only need to add the binding root view instead of the EditText.

EditTextBinding binding = EditTextBinding.inflate(getLayoutInflater());
EditText editText = binding.editText;
View viewToAdd = binding.getRoot();