无法设置“安卓背景”与数据绑定属性,得到一个“对象]不能转换到View”的错误
问题描述:
我有一个TextView像这样:无法设置“安卓背景”与数据绑定属性,得到一个“对象]不能转换到View”的错误
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@{message.isSelf() ? @drawable/bubble_blue : @drawable/bubble_grey}"/>
而且message.isSelf()是只是一个返回布尔值的公共方法。
不过,我得到在编译的时候这个错误:
Error:(125, 141) error: incompatible types: Message cannot be converted to View
走进源代码的错误,这就是问题所在行中产生的数据绑定
var = ((messageIsSelf) ? (getDrawableFromResource(message, R.drawable.bubble_blue)) : (getDrawableFromResource(message, R.drawable.bubble_grey)));
的方法getDrawableFromResource需要一个视图和可绘制的ID作为参数:
/** @hide */
protected static Drawable getDrawableFromResource(View view, int resourceId) {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
return view.getContext().getDrawable(resourceId);
} else {
return view.getResources().getDrawable(resourceId);
}
}
对于某些reaso n,我的消息对象被传递给方法而不是视图。我该如何解决?我试过删除生成文件夹,但仍然没有帮助。
答
原来它,因为我既有“消息”对象,并定义为“消息”,这是引起冲突的TextView中的ID。更改id解决了问题。
答
getDrawableFromResource(message, R.drawable.bubble_grey)));
在你发送一个Message
物体的上述方法(I假设message
是Message
对象),但该方法需要一个View
对象(根据你提供的代码)。这就是你得到这个错误的原因。
尝试使用@android:drawable
注释:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@{message.isSelf() ? @android:drawable/bubble_blue : @android:drawable/bubble_grey}"/>