I\'m building an application that shows different fragments in a ViewPager
. I add these fragments to the ViewPager
like this:
publ
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