7. 转换器

7.1. 对象转换

当 binding 表达式返回对象时,会选择一个 setter(自动 Setter,重命名 Setter,自定义 Setter),将返回对象强制转换成 setter 需要的类型。

下面是一个使用 ObservableMap 保存数据的例子:

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

在这里,userMap 会返回 Object 类型的值,而返回值会被自动转换成 setText(CharSequence) 所需要的类型。当对参数类型存在疑惑时,开发者需要手动做类型转换。

7.2. 自定义转换

有时候会自动在特定类型直接做类型转换。例如,当设置背景的时候:

在这里,背景需要的是 Drawable,但是 color 是一个整数。当需要 Drawable 却返回了一个整数时,int 会自动转换成 ColorDrawable。这个转换是在一个 BindingConversation 注解的静态函数中实现:

@BindingConversion public 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"/>

results matching ""

    No results matching ""