DataBinding(六)数据转换

当一个对象从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类型,如下混合类型是<b>不行</b>的:

<View
   android:background="@{isError ? @drawable/error : @color/white}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容