考虑以下代码:
绑定(bind)适配器:
@BindingAdapter("visibility")
fun setVisibility(view: View, shouldBeVisible: Boolean) {
view.visibility = if (shouldBeVisible) View.VISIBLE else View.GONE
}
像这样使用 bind 命名空间有什么区别:
<TextView
android:id="@+id/text_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
bind:visibility="@{mainViewModel.showTextView}"/>
并像这样使用 app 命名空间:
<TextView
android:id="@+id/text_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:visibility="@{mainViewModel.showTextView}"/>
它们都适用于我的代码。
最佳答案
应用 namespace
应用程序命名空间并不特定于库,但它用于应用程序中定义的所有属性,无论是通过您的代码还是通过您导入的库,有效地为自定义属性创建了一个全局命名空间 - 即未定义的属性由android系统。
在这种情况下,appcompat-v7 库使用镜像 android: 命名空间的自定义属性来支持以前版本的 android(例如:android:showAsAction 仅在 API11 中添加,但 app:showAsAction(作为您的应用程序)适用于您的应用程序执行的所有 API 级别)- 显然,使用 android:showAsAction 不适用于未定义该属性的 API 级别。
- 绑定(bind)
Bind 用于 android 数据绑定(bind)中的自定义 setter 。详情请查看下方
您只需要使用 BindingAdapter 注释来注释静态方法。此注释将字符串作为参数。该字符串是自定义属性,将绑定(bind)到此静态方法。避免在注释参数中添加 namespace ,因为它会使绑定(bind)不稳定。该方法的第一个参数是 View 对象 将函数应用于,第二个参数是从布局 XML 中检索到的值。
@BindingAdapter("progressColor")
public static void setProgressBarColor(ProgressBar loader, int color) {
if (loader != null) {
loader.getIndeterminateDrawable()
.setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_IN);
}
}
了解更多详情
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
bind:progressColor="@{@android:color/holo_green_dark}"
/>
有关绑定(bind)适配器检查的详细信息如下: https://developer.android.com/topic/libraries/data-binding/binding-adapters
关于android - 使用 'bind' 和 'app' 命名空间设置自定义属性与 Android DB 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56503357/