我正在使用 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)类将被标记为可为空。
关于android - 为什么生成的 ViewDataBinding 类将 "include"标记的属性注释为 Nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277809/