Google Data Binding Library 谷歌官方数据绑定库(八)转换

来源:互联网 发布:linux下如何查找文件 编辑:程序博客网 时间:2024/06/05 10:01

本文为菜鸟学习笔记兼翻译练习用,翻译可能会不准确,细节请以原文为准,如有不足之处还请见谅,若能斧正,小弟不胜感激。原文地址:Google Data Binding Library

转换

对象转换

当绑定表达式返回一个对象,一个对应的setter会从自动的、重命名的和自定义的setter当中挑选出来。对象会被转换成setter的参数类型。

使用ObservableMap去保存数据十分方便。例如:

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

userMap返回一个对象,这个对象会被自动的转换成setText(CharSequence)的setter的参数类型。当参数类型比较混乱时,开发者需要在表达式中进行强制转换。

自定义转换

有时特殊类型间需要自动转换。例如,当设置background时:

<View   android:background="@{isError ? @color/red : @color/white}"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>

这里,background使用Drawable,但是颜色是integer。当需要一个Drawable得到的返回值却是一个integer时,int型数据需要转换成ColorDrawable。这个转换可以通过一个被BindingConversion注解修饰的静态方法完成:

@BindingConversionpublic static ColorDrawable convertColorToDrawable(int color) {   return new ColorDrawable(color);}
注意转换只能在setter级别完成,所以下边这种混合类型是不行的:

<View   android:background="@{isError ? @drawable/error : @color/white}"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>

Android Studio对DataBinding的支持

Android Studio对DataBinding代码的编辑特性提供了许多支持。例如下边的几种数据绑定表达式特性:

  • 语法高亮
  • 标明表达式的语法错误
  • XML代码的编译
  • 引入参考,比如引导和快速文档(?)

注意:数组和泛型类型,比如Observable类型,可能会在没有error时仍显示error。

预览窗会显示提供了的绑定表达式的默认值。在下边的例子中引用了布局XML文件中的元素,预览窗在TextView显示了PLACEHOLDER的默认文字。

<TextView android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="@{user.firstName, default=PLACEHOLDER}"/>

如果你需要在你的工程中能在设计时显示默认值,你可以使用tools属性代替默认表达式的值, 参考 Designtime Layout Attributes

Google Data Binding Library的翻译到此结束。

阅读全文
0 0
原创粉丝点击