要将 Databinding 添加到我们的应用程序中,我们需要将以下内容添加到 build.gradle 文件中:

  1. android {
  2. dataBinding {
  3. enabled = true
  4. }
  5. }
  1. android {
  2. ...
  3. buildFeatures {
  4. dataBinding true
  5. }
  6. }

Xml

  1. <layout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:app="http://schemas.android.com/apk/res-auto">
  3. <data>
  4. <variable
  5. name="viewmodel"
  6. type="com.myapp.data.ViewModel" />
  7. </data>
  8. <ConstraintLayout>
  9. <!-- UI layout's root element -->
  10. <TextView
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="@{user.firstName, default=my_default}"/>
  14. </ConstraintLayout>
  15. </layout>

运算符

表达式语言看起来很像托管代码中的表达式。您可以在表达式语言中使用以下运算符和关键字:

  • 数学+ - / * %
  • 字符串连接+
  • 逻辑的&& ||
  • 二进制& | ^
  • 一元+ - ! ~
  • 转移>> >>> <<
  • 比较== > < >= <=(注意<需要转义为<)
  • instanceof
  • 分组()
  • 文字 - 字符、字符串、数字、null
  • 投掷
  • 方法调用
  • 现场访问
  • 数组访问[]
  • 三元运算符?:
    1. android:text="@{String.valueOf(index + 1)}"
    2. android:visibility="@{age > 13 ? View.GONE : View.VISIBLE}"
    3. android:transitionName='@{"image_" + id}'

空合并运算符

空合并运算符 ( ??) 如果不是 则选择左操作数,null 如果前者是 则选择右操作数null。
android:text=”@{user.displayName ?? user.lastName}”

这在功能上等同于:
android:text=”@{user.displayName != null ? user.displayName : user.lastName}”

属性参考

表达式可以使用以下格式引用类中的属性,字段、getter 和 ObservableField 对象的格式相同:
android:text=”@{user.lastName}”

Adapter

  1. @BindingAdapter("app:goneUnless")
  2. fun goneUnless(view: View, visible: Boolean) {
  3. view.visibility = if (visible) View.VISIBLE else View.GONE
  4. }