Gregorio246 Gregorio246 - 1 year ago 84
Android Question

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

I have an

field in my activity class, which is bound to the "checked" attribute of my
like so:


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

Answer Source

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:

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 ...>
        <variable type="com.example.myapp.User" name="user"/>
    <RelativeLayout ...>
        <EditText android:text="@={user.firstName}" .../>

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.

Also, a documentation article about this topic exists already.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download