应用数据绑定适配器以包含标签

Ada*_*331 8 android android-databinding

我在我的项目中使用数据绑定,我有一个用于从视图模型设置可见性条件:

<View
   app:visibilityCondition="@{viewModel.showingItems}" />
Run Code Online (Sandbox Code Playgroud)

这一切都很好,但是突然间我想在这样的包含标签上使用它时:

<include
   layout="@layout/my_include_layout
   app:visibilityCondition="@{viewModel.showingItems}" />
Run Code Online (Sandbox Code Playgroud)

它不会构建,并出现以下错误:

e: [kapt] 发生异常:android.databinding.tool.util.LoggedErrorException:发现数据绑定错误。在 com.example.CustomBinding 上找不到参数类型为 boolean 的属性“app:visibilityCondition”的设置器。

由于CustomBinding该类实际上并未从 扩展View,而是从 扩展ViewDataBinding,因此看起来我没有办法做到这一点。

有没有办法解决这个问题,还是我被迫以编程方式设置这个包含布局的可见性?我知道这会起作用,但如果可能的话,我真的很想将它保留在数据绑定中。

Bar*_*ski 8

显然,目前你是不是能够使用BindingAdaptersincluded布局元素,但是你可以通过附带的布局里面的变量(为他们办理)。

什么凯沙夫AGGARWAL提出几乎是OK。您将不得不includedlayout内部传递数据,但ViewModel在 layout 内部暴露整个数据是不必要的,而且有点不雅。

  1. 修改my_include_layout,添加一个带有绑定参数的变量。
<layout>
    <data>
        <variable
            name="visibilityCondition"
            type="<the_type_of_the_visibility>"/>
    </data>
    <View
        app:visibilityCondition="@{visibilityCondition}"/>
</layout>
Run Code Online (Sandbox Code Playgroud)
  1. 使用bind命名空间在included布局内传递可见性参数:
<include
   layout="@layout/my_include_layout
   bind:visibilityCondition="@{viewModel.showingItems}" />
Run Code Online (Sandbox Code Playgroud)


Ala*_*opf -1

假设您包含的布局仍然根据viewModel第一个代码片段中所示设置可见性条件,并且它必须有一个<data>定义 的部分viewModel,我通常做的是在语句中设置它include。例如:

<include
    bind:viewModel="@{viewModel}"
    layout="@layout/my_include_layout"/>
Run Code Online (Sandbox Code Playgroud)