Replace Fragment inside a ViewPager
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
- update the backing data or page definition
- notify the adapter that the content changed
- 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.
Then update the page through the adapter rather than through a manual fragment transaction:
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.
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, overridinggetItemPositionis 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
- Replacement for deprecated -sizeWithFontconstrainedToSizelineBreakMode in iOS 7?
- Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?
- Request failed unacceptable content-type text/html using AFNetworking 2.0
- Request Permission for Camera and Library in iOS 10 - Info.plist
- Request Permission for Camera and Library in iOS 10 - Info.plist
- resignFirstResponder vs. endEditing for Keyboard Dismissal
- Resize a large bitmap file to scaled output file on Android
- Resize image to full width and fixed height with Picasso
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.