I am following kotlin guide. And I have an error name like this "
"Unresolved reference: newInstance"
How can I fix it?
It's my code in android studio.
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
}
}
It's red on all 'newInstance'.
Did 'newInstance' disappeared as the version changed?
CodePudding user response:
As written in the comments, PageFragment
is not part of the official Android SDK, but rather something you or your colleagues have written yourselves.
Maybe one of your colleagues replaced the function in there, but without seeing the source code for PageFragment
we're unable to help.
Just a quick hint, you can get rid of your var
declarations inside createFragment
by turning the whole function into an expression, e.g.:
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, "", "", "")
}
}