I have an ObservableBoolean
field in my activity class, which is bound to the "checked" attribute of my ToggleButton
like so:
android:checked="@{activity.editing}"
I was hoping this would create a two-way relationship between the button and the boolean, but it only carries changes from the field to the button, not the other way. What am I doing wrong, or is this not in the scope of Android DataBinding
?
Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflate at the other end. For example, if you change the value of the input box, then it will also update the value of the attached property in a component class.
View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files. View binding doesn't support two-way data binding.
Two-way data binding is nothing but updating the data source if there are any changes in the layout and vice versa. Two-way data binding is not applicable for all the views in Android. For example, using two-way data binding in EditText makes sense because users can update the data in the view.
You need another '=' to tell Android that you want to use Two-Way databinding:
android:checked="@={activity.editing}"
You can find more information on this in the wordpress article of George Mount:
Two-Way Data Binding
Android isn’t immune to typical data entry and it is often important to reflect changes from the user’s input back into the model. For example, if the above data were in a contact form, it would be nice to have the edited text pushed back into the model without having to pull the data from the EditText. Here’s how you do it:
<layout ...> <data> <variable type="com.example.myapp.User" name="user"/> </data> <RelativeLayout ...> <EditText android:text="@={user.firstName}" .../> </RelativeLayout> </layout>
Pretty nifty, eh? The only difference here is that the expression is marked with
@={}
instead of@{}
. It is expected that most data binding will continue to be one-way and we don’t want to have all those listeners created and watching for changes that will never happen.
No need to take ObservableBoolean
, you can perform this operation by regular getter-setter method of boolean variable. Like this in your model class
public class User{ private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } }
perform Two-way binding on your ToggleButton
.
<ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="@={user.checked}"/>
and fetch this value by using binding variable.
binding.getUser().isChecked()
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