views-widgets-samples
views-widgets-samples copied to clipboard
ViewPager2 showing some fragments correctly and some as blank screens
I'm using a tabLayout within a parent fragment to provide 5 child fragments to the user. I'm trying to migrate this from ViewPager to ViewPager2.
The issue is that child fragment 0 and 2 are loading, but the other 3 are blank. Using the debugger I found out that the fragment's onCreate
is being called, but it seems like the fragments are instantly detached again.
If I connect the layout inspector it works.
I also tried ViewPager version 1.0.0 and Beta 1.1.0
All the child fragments used to load using ViewPager without any problem, therefore I think this is a ViewPager2 issue and not an issue of my child fragments.
ParentFragment:
class MoreFragment: Fragment() {
private var _binding: FragmentMoreBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
_binding = FragmentMoreBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.viewPager.adapter = TabAdapterKt(childFragmentManager, lifecycle)
TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
tab.text = when (position) {
0 -> getString(R.string.title_clothing)
1 -> getString(R.string.title_chestloot)
2 -> getString(R.string.title_tutorials)
3 -> getString(R.string.title_locations)
4 -> getString(R.string.title_creatures)
else -> "Error"
}
}.attach()
}
}
TabAdapter:
class TabAdapterKt(fragmentManager: FragmentManager, lifecycle: Lifecycle): FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment {
when (position) {
1 -> return ChestLootFragment()
2 -> return TutorialsFragment()
3 -> return LocationsFragment()
4 -> return CreaturesFragment()
else -> return ClothingFragment()
}
}
override fun getItemCount(): Int = 5
}
Fragment loaded:
Fragment hasn't loaded: