微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐