DataBinding(六)数据转换

本文介绍如何在Data Binding中使用ObservableMaps以及自定义转换方法。详细解释了如何通过BindingConversion注解实现不同类型的转换,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当一个对象从binding表达式中返回的时候,就会自动去查找默认、重命名或自定义的setter。然后该对象会被转型成为所选setter的参数类型。这时候对于使用ObservableMaps就很方便,返回的值会自动转换为setter的参数类型,不过如果可能产生混淆的话,还是需要手动去转型。

<TextView
   android:text='@{userMap["lastName"]}'
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>

自定义转换

当表达式返回值是color的int,而setter的方法参数是Drawable时,可以通过BindingConversion注解实现数据转换:

<View
   android:background="@{isError ? @color/red : @color/white}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>
@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
   return new ColorDrawable(color);
}

因为会在setter当中统一进行转换,初始类型必须一致,例如同为颜色值int类型,如下混合类型是不行的:

<View
   android:background="@{isError ? @drawable/error : @color/white}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值