【问题标题】:Warning: 'onCreateView' always returns non-null type警告:“onCreateView”总是返回非空类型
【发布时间】:2020-11-30 14:58:40
【问题描述】:

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

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

onCreateView:

override fun onCreateView(inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    ...
}

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

Android Studio 版本 - 4.1.1。

【问题讨论】:

    标签: android android-studio kotlin


    【解决方案1】:

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

    你的方法返回声明的View?,但我们知道在大多数情况下这个方法不应该返回nullView,所以这个?(空安全)是多余的。只需删除 ?,声明您的方法仅返回 View(在 Kotlin 中默认不为空)

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2010-11-11
      相关资源
      最近更新 更多