Ok, for me, I have been troubleshooting this issue like for 3 hours stright and I got to a point that I made it work this way
Before, I had this inside my ViewPagerStateAdapter
override fun getItemCount(): Int = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
1 -> myFragmentInstance1()
else -> myFragmentInstance2()
}
}
Then for changing the pages I was using the following
private fun navigateTo1() {
binding.viewPager.setCurrentItem(1, false)
}
private fun navigateTo2() {
binding.viewPager.setCurrentItem(2, false)
}
First of all after initializing my viewpager adapter like this
private fun setupViewPager() {
binding.viewPager.apply {
adapter = MyViewPagerStateAdapter(this@MainFragment)
}
}
the initial position inside createFragment
was 0 , so the else block was always called starting my viewpager with the inscance of myFragmentInstance2()
This is not all, after clicking and trying to setCurrentItem to another position the viewpager was changing only once and then it did not work anymore to switch pages
After long times of debug and research I tried to change the positions of the fragments like this
override fun getItemCount(): Int = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> myFragmentInstance1()
else -> myFragmentInstance2()
}
}
which in first place worked for loading 0 as the default destination, and then switching with currentItem worked as expected
private fun navigateTo1() {
binding.viewPager.setCurrentItem(0, false)
}
private fun navigateTo2() {
binding.viewPager.setCurrentItem(1, false)
}
I also tried with
private fun navigateTo1() {
binding.viewPager.currentItem = 0
}
private fun navigateTo2() {
binding.viewPager.currentItem = 1
}
which puts a smoothTransition to true as default and is working fine.
So my conclusion is that the createFragment
initializes our different fragments in a position-based way, starting from 0 and if we start creating our fragments at position 1 it will mess the order and then we will end up having just 1 fragment in the stack to switch.
I did lots of research on the issue but did not found anything related to this issue because if we use TabLayoutMediator
this issue is not happening, it only happens when we try to switch the viewPager programatically with currentItem
"img"
, from the first activity – Leadwort