Build swipeable tabs with ViewPager2
ViewPager2 gives an Android app a smooth, swipeable set of pages while keeping the active tab in sync. Built on RecyclerView, it handles fragments or ordinary views and integrates with Material tabs through TabLayoutMediator. The result is a flexible pattern for account areas, onboarding steps, help topics and other divided screens.
This guide uses Kotlin, XML layouts, FragmentStateAdapter and Material Components. It also covers motion, saved state, accessibility and practical checks for Australian users, including commuters, regional connections and Australian English settings.
Add ViewPager2 and Material dependencies
Open the app-level Gradle file and add the AndroidX pager plus Material Components. These versions are stable examples; use releases that match the rest of your project.
dependencies {
implementation("androidx.viewpager2:viewpager2:1.1.0")
implementation("com.google.android.material:material:1.12.0")
}
ViewPager2 comes from AndroidX, while TabLayout and TabLayoutMediator come from Material. The mediator synchronises tab clicks, swipes and selected-state updates automatically.
Place both views in the same vertical container. Give each a stable ID so Android can restore the selected page after recreation.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Create fragment-backed pages
Give each tab its own fragment and let FragmentStateAdapter manage its lifecycle. This approach works well when pages contain forms, lists or separate business logic rather than simple decorative content.
A compact adapter can expose the tab titles and create the appropriate fragment:
class TabsAdapter(activity: FragmentActivity) :
FragmentStateAdapter(activity) {
override fun getItem(position: Int) =
TabFragment.newInstance(titles[position])
override fun getItemCount() = titles.size
companion object {
val titles = listOf("Overview", "Activity", "Help")
}
}
Each fragment can read its title from arguments, keeping the content independent of its position in the adapter:
class TabFragment : Fragment(R.layout.fragment_tab) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<TextView>(R.id.tabTitle).text =
arguments?.getString(ARG_TITLE)
}
companion object {
private const val ARG_TITLE = "title"
fun newInstance(title: String) = TabFragment().apply {
arguments = Bundle().apply { putString(ARG_TITLE, title) }
}
}
}
FragmentStateAdapter removes fragments that move outside the visible range while retaining their saved state. Avoid storing important data directly in fragment fields, since Android may recreate the fragment after a configuration change or process restoration.
Link the tabs to the pager
Attach the adapter before connecting TabLayoutMediator. The mediator then populates each tab and keeps the selected tab aligned with the visible page.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val pager = findViewById<ViewPager2>(R.id.pager)
val tabs = findViewById<TabLayout>(R.id.tabs)
pager.adapter = TabsAdapter(this)
TabLayoutMediator(tabs, pager) { tab, position ->
tab.text = TabsAdapter.titles[position]
}.attach()
}
Attach the mediator only once and keep it tied to the activity lifecycle. Manual listeners on both views can otherwise trigger duplicate updates, particularly after the pager restores its previous page.
The short labels in the example keep the code compact. In a production app, move user-facing text into strings.xml, then use the corresponding resource identifier in the mediator. This makes the navigation easier to translate and maintain.
Tune gestures, motion and page state
A subtle page transformation can provide feedback during a swipe without interfering with ViewPager2’s default movement. For example, nearby pages can become slightly less opaque.
pager.setPageTransformer { page, position ->
page.alpha = 1f - 0.25f * abs(position).coerceAtMost(1f)
}
Keep the horizontal orientation for conventional tabs. ViewPager2 also supports vertical pages, but vertical swipes can conflict with scrolling inside nested layouts. Use an OnPageChangeCallback for analytics, badge counts or toolbar updates, and unregister it when its owner is destroyed.
Because the pager has a stable ID, Android can restore the selected page when the adapter remains unchanged. Avoid resetting currentItem during startup unless that is intentional. Icon-only tabs need descriptive content descriptions, while visible text labels should remain available wherever possible. Test the flow with TalkBack, enlarged fonts and reduced motion so the tab strip and swiping offer equivalent ways to navigate.
Test for Australian devices and conditions
Try the flow on real phones used across Australian cities, particularly during a trip on Sydney trains or Melbourne trams. One-handed use, rapid page changes and bright outdoor screens make large touch targets, strong contrast and short labels important. A Pixel or Galaxy handset is useful for general testing, while an older or lower-powered device can expose performance problems that an emulator misses.
Regional connections can be less consistent than metropolitan networks, so each tab should load independently and preserve its state when connectivity drops. Cache useful content, provide clear retry options and avoid blocking one page on a request that another page does not need. Retail, banking and transport apps can benefit from this resilient behaviour when customers move between covered and patchy areas.
Use en-rAU resources and check currency, time and date conventions, including 24-hour time and Australian Eastern Standard Time or Daylight Time where relevant. Australian teams often favour relaxed, direct language, so friendly wording such as “We’ll sort that out” can suit customers better than dense corporate phrasing. Use it selectively, though, because a consistent product voice matters more than forced slang. Australian Android users generally reach commercial apps through Google Play, making a Play-delivered build essential for final testing.
Compare, polish and publish your tabs
For an Android Views project, choose the adapter pattern by how much state each page owns. FragmentStateAdapter suits full screens that evolve separately, while a RecyclerView.Adapter suits lightweight, fixed cards. Manual gesture handling adds complexity and should be reserved for a genuinely custom interaction.
| Option | Best fit | Main trade-off |
|---|---|---|
| ViewPager2 with FragmentStateAdapter | Full screens with independent state | More fragment lifecycle management |
| ViewPager2 with RecyclerView.Adapter | Small, fixed cards or simple views | State handling is mostly manual |
| TabLayout without swiping | Settings with direct navigation links | Loses the gesture-driven experience |
| Custom gesture detection | A specialised interaction | Higher testing and maintenance cost |
A dependable release keeps navigation state predictable and verifies the same journey through several input methods.
- Give the pager and tabs stable IDs, and keep each tab label in
strings.xmlfor localisation. - Pass fragment inputs through arguments or a ViewModel instead of relying on a fragment that may be recreated.
- Test swipes, tab taps, TalkBack, font scaling and light and dark themes on physical Android devices.
- Use a staged Google Play rollout, monitor Android vitals for crashes and ANRs, and review customer feedback for accessibility issues.
Build the sample flow in a branch, run it on a phone set to Australian English, and verify both a swipe and a tab tap. Once those paths behave correctly, build the signed Android App Bundle, upload it to Google Play and watch the first rollout for crashes, engagement and feedback across every tab.