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?
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.
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.
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:
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.
This works properly in the new version of Android Studio, which supports binding to LiveData
objects properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With