Search code examples
androiddata-bindingtogglebuttonandroid-databinding

How to perform two-way data binding with a ToggleButton?


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?


Solution

  • 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.