0

代码 A 和代码 B 来自项目https://github.com/android/databinding-samples

代码 B 显示基于图标fun popularityIcon(view: ImageView, popularity: Popularity)并且运行良好。

我发现即使我重命名 @BindingAdapter("app:popularityIcon")为 ,该项目仍然可以正常运行@BindingAdapter("myok:popularityIcon"),就像代码 C 一样,为什么?

代码 A

object BindingAdapters {    
    @BindingAdapter("app:popularityIcon")
    @JvmStatic fun popularityIcon(view: ImageView, popularity: Popularity) {
        val color = getAssociatedColor(popularity, view.context)
        ImageViewCompat.setImageTintList(view, ColorStateList.valueOf(color))
        view.setImageDrawable(getDrawablePopularity(popularity, view.context))
    }
    ...
}

代码 B

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="24dp"
    android:layout_marginTop="24dp"
    android:contentDescription="@string/profile_avatar_cd"
    android:minHeight="48dp"
    android:minWidth="48dp"
    app:layout_constraintBottom_toTopOf="@+id/likes_label"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:layout_constraintVertical_chainStyle="packed"
    app:popularityIcon="@{viewmodel.popularity}"/>

代码 C

object BindingAdapters {    
    @BindingAdapter("myok:popularityIcon")
    @JvmStatic fun popularityIcon(view: ImageView, popularity: Popularity) {
        val color = getAssociatedColor(popularity, view.context)
        ImageViewCompat.setImageTintList(view, ColorStateList.valueOf(color))
        view.setImageDrawable(getDrawablePopularity(popularity, view.context))
    }
    ...
}
4

2 回答 2

1

Databinding ignores namespaces. So it removes app: or myok: or anything else. Also, if you put both adapters with the same name but different namespaces, you would get an error telling you that there are more than one adapter for popularityIcon. You can check the docs for more information.

Note: The Data Binding Library ignores custom namespaces for matching purposes.

于 2020-07-03T23:23:51.093 回答
0

如果您使用此绑定,则需要更新 XML 中的命名空间。像下面

xmlns:myok="http://schemas.android.com/apk/res-auto"

检查下面的代码

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myok="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
...
</androidx.constraintlayout.widget.ConstraintLayout>
于 2020-06-24T12:30:56.967 回答