Home > Back-end >  IllegalArgumentException when Deleting fragments in ViewPager2
IllegalArgumentException when Deleting fragments in ViewPager2

Time:04-25

Hi I've viewPager2 with 5 fragments. Based on a certain condition, I either show all 5 fragments or I want the user to be able to scroll through only 3 of them (page: 1,4,5).

In order to remove the fragments 2 & 3, I did the following but it crashes complaining fragment 2 doesn't exist

private inner class PagerAdapter(fragment:Fragment) : FragmentStateAdapter(fragment) {
val map = mutableMapOf(1 to Frag1, 2 to Frag2, 3 to Frag3, 4 to Frag4, 5 to Frag5)

override fun createFragment(pos: Int): Fragment {
   return if(!map.containsKey(pos)) null else map[pos]!!
}

override getItemCount(): Int = map.size

init {
   if(conditionIsTrue) {
       map.remove(2)
       map.remove(3)
   }
}
}

How can I remove certain fragments from viewPager when certain conditions are met?

Error: When I swipe to move to the next page:

java.lang.IllegalArgumentException: No fragment define for position 2

CodePudding user response:

java.lang.IllegalArgumentException: No fragment define for position 2

This error means that it tries to find the fragment of position 2; but it is not found because the map has only 2 items (position 0, 1).

So, you changed the list size, but that doesn't affect the adapter size.

ViewPager2 internally functions with RecylerView; when we remove/change items in RecyclerView, we have to call adapter.notifyXX methods.

The same is needed in ViewPager2; in your case notifyItemRemoved() need to be called for the deleted positions:

init {
   if(conditionIsTrue) {
       map.remove(2)
       notifyItemRemoved(2)
       map.remove(3)
       notifyItemRemoved(3)
   }
}
  • Related