android - 应用数据绑定(bind)适配器以包含标签

标签 android android-databinding

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

<View
   app:visibilityCondition="@{viewModel.showingItems}" />

一切正常,但是当我想像这样在包含标签上使用它时突然:

<include
   layout="@layout/my_include_layout
   app:visibilityCondition="@{viewModel.showingItems}" />

它没有构建,出现以下错误:

e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors. Cannot find the setter for attribute 'app:visibilityCondition' with parameter type boolean on com.example.CustomBinding.

由于 CustomBinding 类实际上并没有从 View 扩展,而是从 ViewDataBinding 扩展,所以看起来我没有办法做这个。

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

最佳答案

显然,目前您无法将 BindingAdaptersincluded 布局元素一起使用,但您可以在包含的布局中传递变量(供它们处理)。

什么 Keshav Aggarwal建议差不多就可以了。您必须included 布局中传递数据,但是在布局中暴露整个 ViewModel 是不必要的,而且有点不雅观。 p>

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

关于android - 应用数据绑定(bind)适配器以包含标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50722783/

相关文章:

受 url 传播变化启发的 PHP 和服务器层次结构设计

android - 如何 Hook 到 Android 应用程序生命周期?

java - 如何在 Gradle 中排除目录下的所有文件?

java - 发现多个文件的操作系统独立路径为 'android/databinding/DataBindingComponent.java'

android - 如何使用数据绑定(bind)请求或删除对 edittext 的关注

android - 类型不匹配 : inferred type is but was expected

android - "inputType="无 "doesn' t 使用 Material 组件 ExposedDropdownMenu

android - 解析日期在不同的 Android 版本上有不同的值

安卓数据绑定(bind) : conditional formatting to set layout_weight

java - MVVM 中的 Activity/Fragment 和 ViewModel 应该做什么