android data binding jetpack VIII BindingConversionhtml
android data binding jetpack VII @BindingAdapterandroid
android data binding jetpack V 实现recyclerview 绑定源码分析
android data binding jetpack IV 绑定一个方法另外一种写法和参数传递post
android data binding jetpack III 绑定一个方法this
android data binding jetpack II 动态数据更新spa
android data binding jetpack I 环境配置 model-view 简单绑定.net
@BindingConversioncode
绑定转换orm
意思是view某个属性须要一个值,但数据所提供的值跟这个需求有区别。xml
好比:background 须要drawable,但用户提供的是color int值或者是"#FFFFFF"这样的字符窜,那就不能知足了。须要转换一下。
@BindingConversion是用来知足这样的需求的,把“#FFFFFF”转成drawable
用法:
1.在任何一个类里面编写方法,使用@BindingConversion注解。这个与以前的bindingadapter一个用法。很难理解为何这么作,以后再去看源码分析。
2.主法名随便起,叫啥都行。好比 intToDrawable
3.方法必须为公共静态(public static)方法,且有且只能有1个参数
4.重点:方法做用在什么地方的决定因素是:参数类型和返回值类型。两个一致系统自动匹配。
5.转换仅仅发生在setter级别,所以它是不容许如下混合类型:
<View android:background="@{isError ? @drawable/error : @color/white}" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
例子:
/** * 将字符串颜色值转化为ColorDrawable * 随例放哪一个类里都行。随便叫啥都行。 * @param colorString 如:#ff0000 * @return */ @BindingConversion public static ColorDrawable convertColorStringToDrawable(String colorString) { int color = Color.parseColor(colorString); return new ColorDrawable(color); }
咱们在提供数据的类里定义以下:
private String color; public String getColor() { return color; }
在V里绑定时使用他。
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@{student.color}" android:gravity="center" android:text="@{student.name}" android:textSize="18sp" />
效果:

有文章说慎重使用text转int。
使用注意
慎用convertStringToInt:
@BindingConversion
public static int convertStringToInt(String value)
{
int ret;
try {
ret = Integer.parseInt(value);
}
catch (NumberFormatException e)
{
ret = 0;
}
return ret;
}
若是使用databinding的android:text赋值是string类型,会被转换为int类型:
<variable
name="str"
type="String"/>
……………
<TextView
android:id="@+id/id_chute_group_one_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{str}" />
this.idTxt.setText(com.biyou.databinding.Converters.convertStringToInt(str));
运行的时候会报错:
android.content.res.Resources$NotFoundException: String resource ID #0x0
---------------------
做者:逆风Lee
来源:CSDN
原文:https://blog.csdn.net/lixpjita39/article/details/79049872
版权声明:本文为博主原创文章,转载请附上博文连接!
这个错误的缘由是:正好TextView 有setText(int)方法,int 是RES资源。很好理解。
重点 重点 重点:方法做用在什么地方的决定因素是:参数类型和返回值类型。两个一致系统自动匹配。
总结前面两个知识点。
当数据和V的属性不匹配的时候能够有两个作法:
1.定义一个转换方法,使用bindingAdapter 起一个新的属性,在方法里对V进行操做。
2.使用BindingConversion转换成对应的资源类型。也就是本文。