0

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.

4
  • Observer design pattern may be!? Commented Dec 28, 2016 at 8:24
  • 4
    You can implement it with ObservableField Commented Dec 28, 2016 at 8:26
  • DataBinding is used to write less code in your java file, why do you want to implement two-way binding in java code? Commented Dec 28, 2016 at 8:31
  • if you linked your xml to 'user' data model then any changes in datamodel will change the view also! Commented Dec 28, 2016 at 8:31

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.