Skip to content

Instantly share code, notes, and snippets.

@Gnzlt
Last active February 17, 2025 13:31
Show Gist options
  • Save Gnzlt/7e8a23ba0c3b046ed33c824b284d7270 to your computer and use it in GitHub Desktop.
Save Gnzlt/7e8a23ba0c3b046ed33c824b284d7270 to your computer and use it in GitHub Desktop.
FragmentStateAdapter with DiffUtil implementation for ViewPager2
package com.example
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.viewpager2.adapter.FragmentStateAdapter
abstract class DiffFragmentStateAdapter<T> : FragmentStateAdapter {
private val differ: AsyncListDiffer<T>
protected constructor(
fragmentActivity: FragmentActivity,
diffCallback: DiffUtil.ItemCallback<T>
) : super(fragmentActivity) {
differ = AsyncListDiffer(this, diffCallback)
}
protected constructor(
fragment: Fragment,
diffCallback: DiffUtil.ItemCallback<T>
) : super(fragment) {
differ = AsyncListDiffer(this, diffCallback)
}
protected constructor(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
diffCallback: DiffUtil.ItemCallback<T>
) : super(fragmentManager, lifecycle) {
differ = AsyncListDiffer(this, diffCallback)
}
@JvmOverloads
fun submitList(list: List<T>?, commitCallback: Runnable? = null) {
differ.submitList(list, commitCallback)
}
fun getCurrentList(): List<T> =
differ.currentList
protected fun getItem(position: Int): T =
differ.currentList[position]
override fun getItemCount(): Int =
differ.currentList.size
}
package com.example
import androidx.fragment.app.FragmentActivity
import com.example.DiffFragmentStateAdapter
class SampleItemAdapter(fragmentActivity: FragmentActivity) :
DiffFragmentStateAdapter<SampleItem>(fragmentActivity, SampleItem.DiffCallback()) {
override fun createFragment(position: Int): Fragment =
SampleItemFragment.newInstance(getItem(position))
override fun getItemId(position: Int): Long =
getItem(position)
override fun containsItem(itemId: Long): Boolean =
getCurrentList().contains(itemId)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment