为什么我在 Android Studio 中使用数据绑定时可以重命名 @BindingAdapter("app:popularityIcon") 而不会出错?

Why can I rename @BindingAdapter("app:popularityIcon") without error when I use databing in Android Studio?

代码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))
    }
    ...
}

如果您使用此绑定,您需要在 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>

数据绑定忽略名称空间。所以它会删除 app:myok: 或其他任何内容。此外,如果您将两个适配器的名称相同但命名空间不同,您会收到一条错误消息,告诉您 popularityIcon 有多个适配器。 您可以查看 docs 了解更多信息。

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