android - 将支持库更新到 27.0.0 后,我的 fragment 中出现多个错误

将支持库从 v-26.1.0 更新到 v-27.0.0 后,我的 fragment 中出现多个错误。

以下是其中一些错误的列表:

Error: Smart cast to 'Bundle' is impossible, because 'arguments' is a mutable property that could have been changed by this time.

Error: 'onCreateView' overrides nothing

Error: 'onViewCreated' overrides nothing

Error: Type mismatch: inferred type is View? but View was expected

Error: Type mismatch: inferred type is Context? but Context was expected

Error: Type mismatch: inferred type is FragmentActivity? but Context was expected

Error: Type mismatch: inferred type is FragmentActivity? but Context was expected

来自 android studio 的空 fragment 模板。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (arguments != null) {
        mParam1 = arguments.getString(ARG_PARAM1)
        mParam2 = arguments.getString(ARG_PARAM2)
    }
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater!!.inflate(R.layout.fragment_blank, container, false)
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
}

最佳答案

所有这些错误的根本原因是在支持库 v-27.0.0 中添加了 @Nullable@NonNull注解。
并且由于 kotlin 语言意识到可空性并且对于 NullableNonNull 具有不同的类型,这与 Java 不同。
如果没有这些注解,编译器就无法区分它们,Android Studio 正在尽最大努力推断出正确的类型。

TL;DR:更改类型以正确反射(reflect)可空性状态。


Error: Smart cast to 'Bundle' is impossible, because 'arguments' is a mutable property that could have been changed by this time.

更改 arguments.getString(ARG_NAME) ==> arguments?.getString(ARG_NAME) ?: ""


Error: 'onCreateView' overrides nothing

陈:

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

==>

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

Error: 'onViewCreated' overrides nothing

改变:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?)

==>

override fun onViewCreated(view: View, savedInstanceState: Bundle?)

Error: Type mismatch: inferred type is Context? but Context was expected

如果上下文作为参数传递给方法,只需使用快速修复将 getContext() 替换为 getContext()?.let{}
这同样适用于 kotlin 短版 context

else if 用于调用某些方法将 getContext().someMethod() 替换为 getContext()?.someMethod()

同样适用于 kotlin 短版 context?.someMethod()


Error: Type mismatch: inferred type is FragmentActivity? but Context was expected

使用先前错误的修复。

https://stackoverflow.com/questions/47016853/

相关文章:

java - 错误 :Kotlin: Unsupported plugin option: org.

kotlin - 在 Kotlin 中对可空整数使用 "greater than"、 "less t

java - 如何在 Kotlin 中初始化一个线程?

android - 如何混淆我用 kotlin 编码的 sdk(并摆脱元数据)

generics - 如何在 Kotlin 中获取具体泛型参数的实际类型参数?

android - 为全屏 Activity 摆脱不必要的根布局

android - 将 LiveData 与数据绑定(bind)一起使用

sorting - Kotlin 最后排序空值

kotlin - 有什么作用?。在作业的左侧使用时在 Kotlin 中的意思是什么?

android - 延迟对 Kotlin 协程进行单元测试