Helo,

I have a Horizontal Aadapter for a ViewPager:

public class HorizontalAdapter extends FragmentStateAdapter { ... }

Inside the HorizontalAdapter I have creating 3 VerticalContainerFragments, which have an inner Vertical Adapter:

public class VerticalContainerFragment extends Fragment { ... } public class InnerVerticalAdapter extends FragmentStateAdapter { }

The InnverVerticalAdapter has the content with .newInstance() .

I want to refresh the InnerVerticalAdapter wlike that:

doubleViewPagerAdapter.getVerticalViewPager().getAdapter().notifyDataSetChanged();

But this doesn't work. The VerticalViewPager doesn't refresh.

When I try this

doubleViewPager.getAdapter().notifyDataSetChanged();

it also doesn't refresh.

It has no effect. But why?

ubik41's user avatar

This is a known behavior of FragmentStateAdapter in ViewPager2. The default getItemId(position) returns position, so the adapter treats items as unchanged and does not recreate fragments when you call notifyDataSetChanged().

Use stable, unique IDs that change when the data changes.

For example:

public class InnerVerticalAdapter extends FragmentStateAdapter { private long baseItemId = 0; public InnerVerticalAdapter(@NonNull Fragment fragment) { super(fragment); } @Override public Fragment createFragment(int position) { return YourContentFragment.newInstance(position); } @Override public int getItemCount() { return 3; // or your actual count } @Override public long getItemId(int position) { return baseItemId + position; } @Override public boolean containsItem(long itemId) { return itemId >= baseItemId && itemId < baseItemId + getItemCount(); } public void refresh() { baseItemId += getItemCount(); // Invalidate old IDs notifyDataSetChanged(); } }

When you need to refresh, call refresh() instead of notifyDataSetChanged().

Alternative:

If you only need to refresh specific positions:

adapter.notifyItemChanged(position);

This works without overriding getItemId().

Json's user avatar

New contributor

Json is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.