I am using ViewPager2 with FragmentStateAdapter and i am calling notifyItemChanged(position). But as expected createFragment method not calling again. Is it is the intended behavior or bug, what should I do
My Code is
class EEditionPagerAdapter(
fragmentManager: FragmentManager, lifecycle: Lifecycle, private var date: String
) : FragmentStateAdapter(fragmentManager, lifecycle) {
private var menuList = emptyList<EEditionMenu>()
override fun getItemCount(): Int = menuList.size
override fun createFragment(position: Int): Fragment {
val menu = menuList[position]
return EEditionListingFragment.newInstance(menu, date)
}
fun submitList(list: List<EEditionMenu>) {
menuList = list
notifyItemRangeChanged(0, menuList.size)
}
fun changeDate(date: String, position: Int){
this.date = date
notifyItemChanged(position)
}
}
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.
ViewPager2 uses FragmentStateAdapter objects as a supply for new pages to display, so the FragmentStateAdapter will use the fragment class that you created earlier. Create an activity that does the following things: Sets the content view to be the layout with the ViewPager2 .
As we already know that ViewPager2 is built on RecyclerView that's why it's easy to update only one item by calling the method notifyItemChanged(index). If we want to update all items then we can also do this by simply calling the notifyDatasetChanged() method. That's it for now.
FragmentStateAdapter uses item IDs to determine if a fragment has already been created and reuses already created ones. By default, an item ID is the item's position. You can override getItemId
and containsItem
to provide your own unique IDs based on positions and dates, then it will ask for a new fragment when the date changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With