Skip to content Skip to sidebar Skip to footer

Issue On Implementing Viewpager2 With Fragmentstateadapter

I am from ViewPager with FragmentPagerAdapter which has a very straight forward implementation like this. public class FragmentAdapters extends FragmentPagerAdapter { private

Solution 1:

This is weird as overriding

getItemId()
containsItem()

will just give this undesirable behavior when using different kinds of Fragments class I have.

In the end all I need was a simple FragmentStateAdapter class like this

classAppFragmentAdapter(privateval fragmentList: MutableList<Pair<String, Fragment>>, fragment: Fragment) : FragmentStateAdapter(fragment) {

//    private var pageIds = fragmentList.map { fragmentList.hashCode().toLong() }overridefungetItemCount(): Int = fragmentList.size

    overridefuncreateFragment(position: Int): Fragment {
        return fragmentList[position].second
    }

//    override fun getItemId(position: Int): Long = pageIds[position] // Make sure notifyDataSetChanged() works//    override fun containsItem(itemId: Long): Boolean = pageIds.contains(itemId)fungetFragmentName(position: Int) = fragmentList[position].first

    funaddFragment(fragment: Pair<String, Fragment>) {
        fragmentList.add(fragment)
        notifyDataSetChanged()
    }

    funremoveFragment(position: Int) {
        fragmentList.removeAt(position)
        notifyDataSetChanged()
    }

}

Too bad I search for an immediate answer on how to make ViewPager2 dynamic without giving a shot first on the simplest approach I could come up. Many answer here on SO pointing out that getItemId() and containsItem() needs to be override when adding or removing Fragment(s) on ViewPager2 which gives some headache for almost 2 days. Felt betrayed.

Post a Comment for "Issue On Implementing Viewpager2 With Fragmentstateadapter"