Created
July 26, 2019 08:58
-
-
Save matteopasotti/e00e2c4562ccdc2057322061aa51cf4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package app.matteopasotti.com.mymeals.view.adapter | |
import android.util.SparseArray | |
import android.view.ViewGroup | |
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.FragmentManager | |
import androidx.fragment.app.FragmentPagerAdapter | |
import app.matteopasotti.com.mymeals.view.ui.favorites.FavoritesFragment | |
import app.matteopasotti.com.mymeals.view.ui.recents.RecentsFragment | |
import app.matteopasotti.com.mymeals.view.ui.recipes.RecipesFragment | |
class ViewPagerAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { | |
private var registeredFragments = SparseArray<Fragment>() | |
private val baseId : Long = 0 | |
override fun getItemId(position: Int): Long { | |
return baseId + position | |
} | |
override fun getItem(position: Int): Fragment { | |
val result: Fragment | |
when (position) { | |
0 -> result = RecipesFragment.newInstance() | |
1 -> result = FavoritesFragment.newInstance() | |
2 -> result = RecentsFragment.newInstance() | |
else -> result = Fragment() | |
} | |
return result | |
} | |
override fun getCount(): Int { | |
return 3 | |
} | |
override fun getPageTitle(position: Int): CharSequence? = when (position) { | |
0 -> "Recipes" | |
1 -> "Favorites" | |
2 -> "Recents" | |
else -> null | |
} | |
/** | |
* On each Fragment instantiation we are saving the reference of that Fragment in a Map | |
* It will help us to retrieve the Fragment by position | |
* | |
* @param container | |
* @param position | |
* @return | |
*/ | |
override fun instantiateItem(container: ViewGroup, position: Int): Any { | |
val fragment = super.instantiateItem(container, position) as Fragment | |
registeredFragments.put(position, fragment) | |
return fragment | |
} | |
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { | |
registeredFragments.remove(position) | |
super.destroyItem(container, position, `object`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment