ViewPager
Fragment
Android Development
Mobile App
UI/UX

Replace Fragment inside a ViewPager

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Replacing a fragment inside a pager is different from replacing a fragment inside a normal container. The pager owns fragment creation through its adapter, so a direct fragment transaction is usually not the right tool. Instead, you update the adapter’s data and let the pager recreate the page.

Why Direct Fragment Replacement Often Fails

With a ViewPager, fragments are managed by FragmentPagerAdapter or FragmentStatePagerAdapter. With ViewPager2, they are managed by FragmentStateAdapter. In all cases, the adapter is the source of truth.

That means code like “find the current fragment and call replace() on the fragment manager” often fights the pager. The pager may restore its own version later, reuse an existing item, or keep the wrong state cached.

The reliable pattern is:

  1. update the backing data or page definition
  2. notify the adapter that the content changed
  3. let the adapter recreate the affected fragment

Legacy ViewPager Approach

If you are still using the original ViewPager, the adapter usually needs to override getItemPosition so changed fragments are recreated.

java
1public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
2    private final List<Fragment> pages = new ArrayList<>();
3
4    public ScreenSlidePagerAdapter(FragmentManager fm) {
5        super(fm);
6    }
7
8    @Override
9    public Fragment getItem(int position) {
10        return pages.get(position);
11    }
12
13    @Override
14    public int getCount() {
15        return pages.size();
16    }
17
18    @Override
19    public int getItemPosition(Object object) {
20        return POSITION_NONE;
21    }
22
23    public void replacePage(int index, Fragment fragment) {
24        pages.set(index, fragment);
25        notifyDataSetChanged();
26    }
27}

Then update the page through the adapter rather than through a manual fragment transaction:

java
adapter.replacePage(1, DetailsFragment.newInstance("updated"));
viewPager.setCurrentItem(1, false);

Returning POSITION_NONE tells the legacy pager that existing fragment instances are no longer valid and should be recreated.

Modern ViewPager2 Approach

For new code, prefer ViewPager2. It uses RecyclerView under the hood and works better with a stable item model.

A clean approach is to keep a list of page descriptors and recreate fragments from that list.

kotlin
1class PagerAdapter(
2    fragment: Fragment,
3    private val pages: MutableList<String>
4) : FragmentStateAdapter(fragment) {
5
6    override fun getItemCount(): Int = pages.size
7
8    override fun createFragment(position: Int): Fragment {
9        return DetailsFragment.newInstance(pages[position])
10    }
11
12    override fun getItemId(position: Int): Long {
13        return pages[position].hashCode().toLong()
14    }
15
16    override fun containsItem(itemId: Long): Boolean {
17        return pages.any { it.hashCode().toLong() == itemId }
18    }
19
20    fun replacePage(index: Int, value: String) {
21        pages[index] = value
22        notifyDataSetChanged()
23    }
24}

The stable item ID methods help ViewPager2 understand when a page is genuinely the same logical item and when it should be recreated.

Preserve State Intentionally

When you replace a pager fragment, ask whether you truly want replacement or just UI refresh. If the fragment represents the same logical page and only its content changed, a shared ViewModel or callback may be better than destroying and recreating the fragment.

For example, a “profile” page whose displayed username changes usually does not need replacement. The fragment can observe state and redraw itself. Replacement makes more sense when the page type itself changes, such as switching from a summary page to an error page.

That distinction matters because fragment recreation drops transient UI state unless you preserve it explicitly.

Common Pitfalls

The most common mistake is calling FragmentTransaction.replace() on a fragment that the pager adapter manages. The adapter usually wins, and the result becomes inconsistent.

Another frequent issue is forgetting to notify the adapter after changing the data source. Without that notification, the pager has no reason to recreate anything.

In legacy ViewPager, developers also often skip getItemPosition, so the pager keeps the old fragment instance cached.

Finally, do not replace fragments when a state update would do. If the page identity is unchanged, a ViewModel or explicit update method is often simpler and preserves user state better.

Summary

  • In a pager, the adapter controls fragment lifecycle, not ad hoc fragment transactions.
  • Replace pages by updating adapter data and notifying the adapter.
  • For legacy ViewPager, overriding getItemPosition is often required to force recreation.
  • For ViewPager2, prefer stable item IDs and a model-driven adapter.
  • If the page is the same logical screen, consider updating state instead of replacing the fragment.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.