这些代码有效。我创建Fragment根据这些布尔值是假或真。但我想用更少的代码。我只是试着把它们加到for循环中,但它也变长了。我如何用更少的代码动态地在这里创建片段?我在stackOverflow和互联网上找不到解决方案。
class ReportASMViewPagerAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val visitId: String,
private val facilityId: String,
private val tabItemCount: Int,
private val hasLabResult: Boolean,
private val hasRadResult: Boolean
) : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return tabItemCount
}
override fun createFragment(position: Int): Fragment {
if (hasLabResult && hasRadResult) {
return when (position) {
0 -> {
LaboratoryASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
1 -> {
RadiologyASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
2 -> {
PrescriptionASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
3 -> {
OtherReportsASMFragment()
}
else -> {
Fragment()
}
}
} else if (hasLabResult && !hasRadResult) {
return when (position) {
0 -> {
LaboratoryASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
1 -> {
PrescriptionASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
2 -> {
OtherReportsASMFragment()
}
else -> {
Fragment()
}
}
} else {
return when (position) {
0 -> {
RadiologyASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
1 -> {
PrescriptionASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
}
2 -> {
OtherReportsASMFragment()
}
else -> {
Fragment()
}
}
}
}
}
你可以使用下面的代码,但我认为你的代码更容易读:
override fun createFragment(position: Int): Fragment {
var newPosition = position
if (hasLabResult && hasRadResult) {
newPosition = position
} else if (hasLabResult && !hasRadResult) {
if (position >= 1) newPosition = position + 1
} else {
if (position != 0) newPosition = position + 1
}
return when (newPosition) {
0 -> LaboratoryASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
1 -> RadiologyASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
2 -> PrescriptionASMFragment.newInstance(referenceVisitId = visitId, facilityId = facilityId)
3 -> OtherReportsASMFragment()
else -> Fragment()
}
}