Last active
March 24, 2023 02:01
-
-
Save victory316/61db1832ba509eab2753fefde6be49c6 to your computer and use it in GitHub Desktop.
ViewPager2 Adapter to use with Fragments which is dynamically added or removed.
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
data class FragmentData(val pageId: String) | |
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
class FragmentPagerAdapter( | |
val items: MutableList<FragmentData> = mutableListOf(), | |
context: FragmentActivity, | |
) : FragmentStateAdapter(context) { | |
override fun getItemCount(): Int = items.size | |
override fun createFragment(position: Int): Fragment { | |
return MyFragment | |
} | |
override fun getItemId(position: Int): Long = itemId(position) | |
override fun containsItem(itemId: Long): Boolean = contains(itemId) | |
fun submitList(list: List<FragmentData>) { | |
items.clear() | |
items.addAll(list) | |
} | |
fun changeDataSet(performChanges: () -> Unit) { | |
val idsOld: List<String> | |
val idsNew: List<String> | |
idsOld = createIdSnapshot() | |
performChanges() | |
idsNew = createIdSnapshot() | |
DiffUtil.calculateDiff(object : DiffUtil.Callback() { | |
override fun getOldListSize(): Int = idsOld.size | |
override fun getNewListSize(): Int = idsNew.size | |
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = | |
idsOld[oldItemPosition] == idsNew[newItemPosition] | |
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = | |
areItemsTheSame(oldItemPosition, newItemPosition) | |
}, false).dispatchUpdatesTo(this) | |
} | |
private fun createIdSnapshot() = items.map { it.pageId } | |
private fun itemId(position: Int): Long = items[position].pageId.toLong() | |
private fun contains(itemId: Long): Boolean = items.any { items.any { it.pageId.toLong() == itemId } } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment