数据绑定时导入和变量之间的区别?

Difference between import and variable when Data Binding?

在查看 Data Binding documentation 了解 <import/><variable/> 之间的区别后,不清楚它们有何不同。以下是从文档页面中获取的示例。

<import type="com.example.real.estate.View" alias="Vista"/>

看起来相当于

<variable name="user" type="com.example.User"/>

除了 alias 可以以大写字母开头,而 name 不能。它们甚至被类似地使用。

<data>
    <import type="com.example.MyStringUtils"/>
    <variable name="user" type="com.example.User"/>
</data>
…
<TextView
   android:text="@{MyStringUtils.capitalize(user.lastName)}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>

我从示例中看到的唯一区别是您可以调用 import 的方法,但不能调用 variable 的方法。

如果您想将一些数据传递给视图,请使用 variable。在您的示例中,您有 User 类型的用户变量,您使用它在 TextView 中设置用户名。您可以调用变量方法 - user.lastName 等同于 user.getLastName()

使用 import 您只指定要使用的 class,您不传递任何数据。在您的示例中,导入的实用程序 class 仅用于将用户名大写,capitalize 方法将其作为参数接收。