如何使用ToggleButton执行双向数据绑定? [英] How to perform two-way data binding with a ToggleButton?

查看:218
本文介绍了如何使用ToggleButton执行双向数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动类中有一个ObservableBoolean字段,该字段绑定到我的ToggleButton的"checked"属性中,如下所示:

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}"

我希望这会在按钮和布尔值之间建立双向关系,但它只会携带从字段到按钮的更改,而不会包含其他更改.我在做什么错,还是这不在Android DataBinding的范围内?

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?

推荐答案

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

You need another '=' to tell Android that you want to use Two-Way databinding:

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

您可以在中找到更多信息在George Mount的wordpress文章中:

双向数据绑定

Android不能避免典型数据输入,因此将用户输入的更改反映回模型中通常很重要.例如,如果以上数据为联系表,那么将编辑后的文本推回模型中而不必从EditText中提取数据将是很好的选择.操作方法如下:

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执行双向数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆