Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText LiveData Two-way binding

Okay, so I have a ViewModel with a getter getTitle() that returns MutableLiveData<String>.

<EditText
    style="@style/Widget.EditText.FullWidth"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/label_title"
    android:inputType="text"
    android:text="@={ viewModel.title }" />

This works fine at first: the EditText contains the value of the MutableLiveData when it first appears. However, if the value of this data is updated using MutableLiveData.setValue() (such as by another EditText, or from my code), then the value inside of the text box does not change. How do I fix this?

like image 831
laptou Avatar asked Apr 08 '18 23:04

laptou


People also ask

What is the two-way binding in edittext?

Usually, we apply the two-way binding in our EditText. When the EditText is changes by the user input, the attribute in model that binds to this EditText also changes. We’ll use this type of binding to helps us solve this problem with less code and callbacks.

How do I use a livedata object with a binding class?

To use a LiveData object with your binding class, you need to specify a lifecycle owner to define the scope of the LiveData object. The following example shows how to set the activity as the lifecycle owner after the binding class has been instantiated: // Inflate view and obtain an instance of the binding class.

How do I use two-way data binding with custom attributes?

If you want to use two-way data binding with custom attributes, you need to work with the @InverseBindingAdapter and @InverseBindingMethod annotations. For example, if you want to enable two-way data binding on a "time" attribute in a custom view called MyView, complete the following steps:

What is two-way data binding in Java?

Two-way Data Binding is a technique of binding your objects to your XML layouts so that the layout can send data to your binding object. This is compared to a “traditional” or “one-way” Data Binding setup, where data would only move from your binding object to the layout.


1 Answers

This works properly in the new version of Android Studio, which supports binding to LiveData objects properly.

like image 147
laptou Avatar answered Oct 25 '22 20:10

laptou