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

时间:2018-09-04 17:58:59

标签: android android-databinding

在检查<import/><variable/>之间的区别之后,Data Binding documentation尚不清楚它们之间的区别。以下是从文档页面获取的示例。

<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的方法。

1 个答案:

答案 0 :(得分:1)

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

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