无法使用数据绑定设置 "android:background" 属性,出现 "object] cannot be converted to View" 错误

Can't set "android:background" attribute with databinding, get a "object] cannot be converted to View" error

我有一个像这样的 Textview:

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@{message.isSelf() ? @drawable/bubble_blue : @drawable/bubble_grey}"/>

而 message.isSelf() 只是一个 public 方法,returns 一个布尔值。

但是,我在尝试编译时遇到此错误:

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 将 View 和 drawable 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);
        }
    }

出于某种原因,我的消息对象被传递给方法而不是视图。我该如何解决?我已尝试删除构建文件夹,但仍然无济于事。

getDrawableFromResource(message, R.drawable.bubble_grey)));

在上面的方法中你发送了一个 Message 对象(我假设 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}"
/>

原来是因为我有一个 "message" 对象和定义为 "message" 的 TextView 的 ID,这导致了冲突。更改id解决了问题。