android - 为什么生成的 ViewDataBinding 类将 "include"标记的属性注释为 Nullable

标签 android kotlin android-databinding

我正在使用 Android 数据绑定(bind)库来绑定(bind)具有 <include> 的 xml 布局

布局.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="model"
            type="com.example.MyViewModel" />
    </data>

    ...

    <include
        layout="@layout/someOtherLayout"
        android:id="@+id/includedLayout" />
    ...

</layout>

在为 xml 生成的数据绑定(bind)类中,我看到了这个属性:

@Nullable
public final com.example.databinding.SomeOtherLayoutBinding includedLayout;

为什么注释为@Nullable<include>在布局中,正如我所见,它显然是非空的。我错过了什么?

它迫使我使用非空断言运算符 !!在访问包含的布局的字段时在 Kotlin 代码中,我想知道它是否安全或者是否有我在这里没有考虑的东西

val binder = DataBindingUtil.bind(view)
val someView = binder.includedLayout!!.someView

最佳答案

根据 View Binding 文档,当您有多个布局更改配置时,如果 View 仅出现在某些配置中,则绑定(bind)类将被标记为可为空。

View Binding Docs

关于android - 为什么生成的 ViewDataBinding 类将 "include"标记的属性注释为 Nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277809/

相关文章:

android - Android-具有LiveData的DataBinding保留旧值

android - 带构造函数的房间类型转换器

android - 微调器控件不显示所选文本

unit-testing - 模拟属性 setter

android - 带有@Parcelize 注解的RealmList

android - 使用数据绑定(bind)在 PagerAdapter 中回收 View

android - 事件发生时错误的 Lambda 表达式评估

java - 用于关闭对话框的按钮引发 nullpointerException

android - 屏幕锁定时 Activity 返回纵向

kotlin - Kotlin "assign value exactly once on the first call"如何表达?