Android 使用srcCompat进行数据绑定

Android 使用srcCompat进行数据绑定,android,android-support-library,android-databinding,Android,Android Support Library,Android Databinding,我在supportlibv23.2中使用了新的vectordrawable支持,app:srcCompat&试图通过数据绑定设置它的drawable <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> <variable name="

我在supportlibv23.2中使用了新的vectordrawable支持,app:srcCompat&试图通过数据绑定设置它的drawable

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="mediaPojo"
        type="in.ishaan.pika.data_binding.MediaPojo"/>
</data>

<RelativeLayout
    android:background="@color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <VideoView
        ... />

    <ImageView
        ...
        app:srcCompat="@{mediaPojo.isPlaying ? @drawable/ic_pause_24dp : @drawable/ic_play_arrow_24dp}"
    />

    <ProgressBar
        .../>
</RelativeLayout>
</layout>

在尝试构建时,studio抛出:

错误:(33,30)找不到参数类型为android.graphics.drawable.drawable的属性“app:srcCompat”的setter


您可能必须使用具有类似以下方法签名的绑定适配器:

@BindingAdapter("app:srcCompat")
public static void bindSrcCompat(ImageView imageView, Drawable drawable){
    // Your setter code goes here, like setDrawable or similar
}

这里是参考:

当您通过数据绑定设置向量资源时,您可以简单地使用android:src属性而不是compat属性

数据绑定库生成在运行时执行setImageResource方法的类

<ImageView
        ...
        android:src="@{@drawable/your_drawable}"
/>

建议的答案主要适用于我,但我还需要在我的申请中添加这一行:

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

这样做可以让我在旧版本中使用vector drawables,而无需担心compat类或属性

如果您需要使用srccomat,还需要在drawables上通过xml设置色调,最简单的方法是使用android.support.v7.widget。AppCompatImageView

然后,android:tintapp:srcCompat工作正常


注意:由于一些我不知道的原因,在使用ImageView的片段布局中工作正常。只有在活动布局中才需要恢复到AppCompatImageView。

是否包含
xmlns:app=”http://schemas.android.com/apk/res-auto“
布局根元素的属性?@PaulDS是的,让我用完整布局更新问题“数据绑定库生成在运行时执行setImageResource方法的类。”你确定吗?您无法打开绑定类,那么我们如何确定呢?我检查了两件事:1。使用android:src属性和数据绑定时,在lolipop之前的设备上显示vector drawable(它毫无例外地显示)2。在谷歌工作的一位软件工程师在这里(ExpressionTree(8:01)一节)谈到了如何将src属性与setImageResource方法相匹配。此外,您可以尝试在代码ImageViewBindingAdapter中查找。它是数据绑定库中用于绑定ImageView的适配器。在生成的代码中,可以找到对此适配器的引用。您可以使用NotePad++打开生成的类(例如:),因为Android Studio默认打开xml布局。它们存储在app\build\intermediates\classes\your\package\name\DataBinding中我注意到事实上,数据绑定生成的代码使用setImageDrawable+getDrawableFromResource方法:),但它按预期工作。请记住,使用此标志会导致内存问题(),我必须删除
app:
部分才能编译它。
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);