How to get the instance of the currently visible fragment in ViewPager:

后端 未结 3 1441
一生所求
一生所求 2021-01-06 23:28

I\'m building an application that shows different fragments in a ViewPager. I add these fragments to the ViewPager like this:

 publ         


        
3条回答
  •  囚心锁ツ
    2021-01-07 00:03

    The way I do it as of year 2020 in Kotlin:

    Inside the fragment class I add a public variable:

    var fragmentNo = 0
    

    The fragmentNo variable is filled through the adapter's getItem as follows (note fragment.fragmentNo = pos) in particular:

        private inner class ViewPagerAdapter(fragmentManager: FragmentManager)
            : FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    
            override fun getCount(): Int = list.size
            var position = 0
            lateinit var fragment: ExerciseFragment
    
            override fun getItem(pos: Int): Fragment {
                fragment = ExerciseFragment()
                position = pos
                val bundle = Bundle()
                bundle.putSerializable(Constants.WORD_ID, list[position])
                fragment.arguments = bundle
                fragment.fragmentNo = pos
                return fragment
            }
    
        }
    

    Afterwards, I use the visible fragment in a button clicker, which is outside the viewpager, as follows:

    btShowAnswer.setOnClickListener {
                Logger.print(this, "Show Answer Button clicked")
    
                val fr: ExerciseFragment? = supportFragmentManager.fragments.find {
                    it is ExerciseFragment && it.fragmentNo == viewPager.currentItem
                } as? ExerciseFragment
    
                fr?.showAnswer()
    
            }
    

    The below line finds the required fragment in particular:

    val fr: ExerciseFragment? = supportFragmentManager.fragments.find {
                    it is ExerciseFragment && it.fragmentNo == viewPager.currentItem
                } as? ExerciseFragment
    

提交回复
热议问题