其他分享
首页 > 其他分享> > android – 如何使用ToggleButton执行双向数据绑定?

android – 如何使用ToggleButton执行双向数据绑定?

作者:互联网

我的activity类中有一个ObservableBoolean字段,它绑定到我的ToggleButton的“checked”属性,如下所示:

android:checked="@{activity.editing}"

我希望这会在按钮和布尔值之间创建双向关系,但它只会从字段到按钮进行更改,而不是其他方式.我做错了什么,或者这不在Android DataBinding的范围内?

解决方法:

您需要另一个’=’来告诉Android您要使用双向数据绑定:

android:checked="@={activity.editing}"

你可以在这个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.

标签:togglebutton,android,data-binding,android-databinding
来源: https://codeday.me/bug/20191005/1855302.html