Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pjonceski/e08db9a6a396b190a9df04bbf29f7675 to your computer and use it in GitHub Desktop.
Save pjonceski/e08db9a6a396b190a9df04bbf29f7675 to your computer and use it in GitHub Desktop.
/**
* This class is FragmentPagerAdapter where all the fragments are in an array and you can access to them later.
* @property mFragments the list of fragments,
* @property NUMBER_OF_FRAGMENTS the total number of fragments that will be created. Change the value of this param accordingly.
*/
class MyFragmentPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
companion object {
private val NUMBER_OF_FRAGMENTS = 2
}
private val mFragments = SparseArray<Fragment>()
override fun getCount(): Int {
return NUMBER_OF_FRAGMENTS
}
override fun getItem(position: Int): Fragment {
TODO("Here you create and return the fragment instances")
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val fragment = super.instantiateItem(container, position) as Fragment
mFragments.put(position, fragment)
return fragment
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
mFragments.remove(position)
super.destroyItem(container, position, `object`)
}
/**
* Returns the instance of the fragment if it is created, null otherwise.
*/
fun getFragment(position: Int): Fragment? {
return if (mFragments.size() == 0) {
null
} else mFragments.get(position)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment