警告:“onCreateView”总是返回非空类型

Ars*_*aev 8 android kotlin android-studio

今天我在我所有的片段中发现了这个警告:

警告:(45, 12) 'onCreateView' 总是返回非空类型

onCreateView:

override fun onCreateView(inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    ...
}
Run Code Online (Sandbox Code Playgroud)

问题是,发生了什么变化,为什么?

Android Studio 版本 - 4.1.1。

sna*_*msm 9

这是Kotlin警告,可能是新的 lint 检查以帮助您生成质量更好的代码

您的方法返回 声明View?,但正如我们所知,在大多数情况下,此方法不应返回null View,因此此?(空安全)是多余的。只需删除?,声明您的方法只返回View(在 Kotlin 中默认不为 null)

override fun onCreateView(inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View { // in here no "?"
    ...
}
Run Code Online (Sandbox Code Playgroud)

顺便提一句。DOC说这个方法可能会返回nullFragment表现得就像一些对象/数据持有者一样,没有 UI,只是为了在Activitys 生命周期中正确保留实例。但在这种情况下,开发不会被覆盖onCreateView在所有