首页 文章

将支持库更新到27.0.0后,我的片段中出现多个错误

提问于
浏览
22

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

这里列出了一些错误:

错误:智能转换为'Bundle'是不可能的,因为'arguments'是一个可变属性,此时可能已被更改 . 错误:'onCreateView'不会覆盖任何错误:'onViewCreated'不会覆盖任何错误:类型不匹配:推断类型是View?但是View是预期的错误:类型不匹配:推断类型是Context?但上下文是预期错误:类型不匹配:推断类型是FragmentActivity?但上下文是预期错误:类型不匹配:推断类型是FragmentActivity?但是上下文是预期的

来自android studio的空片段模板 .

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)
}

1 回答

  • 38

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

    TL;DR: change the types to rightly reflect the nullability status.


    错误:智能转换为'Bundle'是不可能的,因为'arguments'是一个可变属性,此时可能已被更改 .

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


    错误:'onCreateView'不会覆盖任何内容

    CHANE:

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

    ==>

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

    错误:'onViewCreated'不会覆盖任何内容

    更改:

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

    ==>

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

    错误:类型不匹配:推断类型是上下文?但是上下文是预期的

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

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

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


    错误:类型不匹配:推断类型是FragmentActivity?但是上下文是预期的

    使用上一个错误的修复程序 .

相关问题