未解决的参考:newInstance?

Unresolved reference: newInstance?

我正在关注 kotlin 指南。我有一个像这样的错误名称“

"Unresolved reference: newInstance"

我该如何解决?

这是我在 android 工作室的代码。

inner class PagerAdapter : FragmentStateAdapter {
        constructor(fm: FragmentManager, lc: Lifecycle) : super(fm, lc)

        override fun getItemCount() = 3

        override fun createFragment(position: Int): Fragment {
            var imageId:Int = 0
            var title:String = ""
            var details1:String = ""
            var details2:String = ""
            var fragment:PageFragment? = null

            when(position) {
                0 -> {
                    imageId = R.drawable.poster1
                    title = "${position+1}. name"
                    details1 = "312,745"
                    details2 = "15"

                    fragment = PageFragment.newInstance(imageId, title, details1, details2)
                }
                1 -> {
                    imageId = R.drawable.poster2
                    title = "${position+1}. name"
                    details1 = "166,604"
                    details2 = "15"

                    fragment = PageFragment.newInstance(imageId, title, details1, details2)
                }
                2 -> {
                    imageId = R.drawable.poster3
                    title = "${position+1}. name"
                    details1 = "51,608"
                    details2 = "12"

                    fragment = PageFragment.newInstance(imageId, title, details1, details2)
                }
                else -> {
                    fragment = PageFragment.newInstance(0, "", "", "")
                }
            }

            return fragment
        }
    }

所有 'newInstance' 都是红色的。

'newInstance'是不是随着版本的变化消失了?

如评论中所写,PageFragmentnot part of the official Android SDK,而是您或您的同事自己写的东西。

也许您的一位同事替换了其中的函数,但没有看到 PageFragment 的源代码,我们无法提供帮助。


只是一个快速提示,您可以通过将整个函数转换为表达式来摆脱 createFragment 中的 var 声明,例如:

override fun createFragment(position: Int): Fragment {
    return when (position) {
        0 -> PageFragment.newInstance(
            imageId = R.drawable.poster1,
            title = "${position + 1}. name",
            details1 = "312,745",
            details2 = "15",
        )
        1 -> PageFragment.newInstance(
            imageId = R.drawable.poster2,
            title = "${position + 1}. name",
            details1 = "166,604",
            details2 = "15",
        )
        2 -> PageFragment.newInstance(
            imageId =R.drawable.poster3,
            title = "${position + 1}. name",
            details1 = "51,608",
            details2 = "12",
        )
        else -> PageFragment.newInstance(0, "", "", "")
    }
}