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
?
No need to take
ObservableBoolean
, you can perform this operation by regular getter-setter method of boolean variable. Like this in your model classperform Two-way binding on your
ToggleButton
.and fetch this value by using binding variable.
You need another '=' to tell Android that you want to use Two-Way databinding:
You can find more information on this in the wordpress article of George Mount:
Here are ways to set
OnCheckedChangeListener
in data binding:(1) Set by method expression
In layout
In Activity
(2) Set by lambda expression and method call
In Activity
(3) Pass
OnCheckedChangeListener
anonymous class to layoutIn Activity
(4) Pass
OnCheckedChangeListener
by referenceActivity
This will never work
Because you can't set two callback on one component. One callback is already set by two way binding, so your callback will not work.
Check CompoundButtonBindingAdapter class to see how Switch Binding works.
Here's a simple example of a 2-way databinding using a Switch, which also has the Checked property, like the ToggleButton.
Item.java:
MainActivity.java:
activity_main.xml:
build.gradle:
Source documentation: https://developer.android.com/topic/libraries/data-binding/index.html