Hello all, I’ve got one weird issue with `ViewPage...
# android
a
Hello all, I’ve got one weird issue with
ViewPager2
and I cannot make any sense of it, I’ve got separate
Activity
that holds
ViewPager2
which contains fragments. That means destroying that activity with
finish()
closes
ViewPager2
as well. Now what I’ve got is beyond me, everything works fine when I start it for the first time, but if I close it and reopen my observables in the fragments won’t emit any changes, tho everything is created fine?. I’ve pinpointed issue to the
createFragment
method where commented part works but non commented doesn’t?
Copy code
class PagerAdapter( 
    fragmentActivity: FragmentActivity,
    private val items: List<PagerAdapterFragment>
    //private val items: List<Int>
) : FragmentStateAdapter(fragmentActivity) {

    override fun createFragment(position: Int): Fragment {
        return items[position].fragment
//        return when (position) {
//            0 -> Fragment1.newInstance()
//            1 -> Fragment2.newInstance()
//            2 ->  PlaceholderFragment.newInstance("Retention information screen")
//            else ->  PlaceholderFragment.newInstance("Else")
//        }
    }

    data class PagerAdapterFragment(val id: Long, val fragment: Fragment)
Oke fixed it with:
Copy code
override fun createFragment(position: Int): Fragment {
     return when (items[position].id) {
          ID_FRAG_1 -> Fragment1.newInstance()
          ID_FRAG_2 -> Fragment2.newInstance()
          ID_FRAG_3 -> Fragment3.newInstance()
          else -> PlaceholderFragment.newInstance("Else")
        }
    }
I don’t understand completely whats going on, tried debugging couldn’t find anything useful. I guess it needs
else
as fail safe tho fragments were initialising without it just fine
i
You must always return a brand new Fragment instance from
createFragment
, that's why it is called create and not get
a
Hi @Ian Lake thanks for reply, that
get
was returning
newIstance()
of a Fragment. This is basically the same code, and when running the app Fragments were initialised properly, just for some reason observing wasn’t working.
i
Well, it very much looked like you were passing in a set of Fragment instances and calling
items[position].fragment
to return a previously created instance...not a brand new instance every single time
createFragment
was called
👍 1