Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentStateAdapter for ViewPager2 notifyItemChanged not working as expected

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)
    }
}
like image 936
Karthick Ramanathan Avatar asked Feb 26 '20 06:02

Karthick Ramanathan


People also ask

What is the difference between ViewPager and ViewPager2?

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 .

How do I refresh Fragmentpageradapter?

You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.

What is ViewPager2 in android?

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 .

How do I refresh 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.


1 Answers

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.

like image 66
StenSoft Avatar answered Sep 22 '22 17:09

StenSoft