Get current fragment with ViewPager2

后端 未结 11 1852
野的像风
野的像风 2020-12-24 01:15

I\'m migrating my ViewPager to ViewPager2 since the latter is supposed to solve all the problems of the former. Unfortunately, when using it with a

11条回答
  •  隐瞒了意图╮
    2020-12-24 01:47

    I had similar problem when migrating to ViewPager2.

    In my case I decided to use parentFragment property (I think you can make it also work for activity) and hope, that ViewPager2 will keep only the current fragment resumed. (i.e. page fragment that was resumed last is the current one.)

    So in my main fragment (HostFragment) that contains ViewPager2 view I created following property:

    private var _currentPage: WeakReference? = null
    val currentPage
        get() = _currentPage?.get()
    
    fun setCurrentPage(page: MyPageFragment) {
        _currentPage = WeakReference(page)
    }
    

    I decided to use WeakReference, so I don't leak inactive Fragment instances

    And each of my fragments that I display inside ViewPager2 inherits from common super class MyPageFragment. This class is responsible for registering its instance with host fragment in onResume:

    override fun onResume() {
        super.onResume()
        (parentFragment as HostFragment).setCurrentPage(this)
    }
    

    I also used this class to define common interface of paged fragments:

    abstract fun someOperation1()
    
    abstract fun someOperation2()
    

    And then I can call them from the HostFragment like this:

    currentPage?.someOperation1()
    

    I'm not saying it's a nice solution, but I think it's more elegant than relying on internals of ViewPager's adapter with instantiateItem method that we had to use before.

提交回复
热议问题