Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 104 ยท Building a Real UI

Tabs and Pagers in Compose

Build swipeable tabs in Jetpack Compose with PrimaryTabRow, ScrollableTabRow and HorizontalPager, sync them through PagerState, add page indicators and set page sizes.

Tabs let a screen offer a few parallel views of the same area, such as "Chats", "Status" and "Calls", without leaving the screen. A pager lets the user swipe sideways between full pages, like an onboarding flow or a photo gallery. They are often combined: the tabs show where you are, the pager holds the content, and swiping or tapping either one moves both.

In Compose these are two independent pieces: a tab row from Material 3 and HorizontalPager (or VerticalPager) from androidx.compose.foundation. Nothing links them by magic. You connect them with a shared PagerState. This lesson shows each piece, the syncing pattern, page indicators and page sizes. The Android UI cannot run here, so the real Compose code is read-only; the TryIts are plain Kotlin stand-ins that model how a pager state behaves (current page, target page, scroll offset) so the numbers are visible.

Tab rows

Material 3 has three tab composables for the row itself:

  • PrimaryTabRow for the main navigation inside a screen, with an indicator line under the selected tab. This is the one to use first.
  • SecondaryTabRow for sub-sections inside a page, with a lighter, full-width indicator.
  • PrimaryScrollableTabRow / SecondaryScrollableTabRow when you have many tabs or long titles; the row scrolls sideways and tabs keep their natural width.

Older code uses TabRow and ScrollableTabRow, which are deprecated in recent Material 3 versions in favor of the primary/secondary variants. Check the version you use; the shape of the API is the same.

Kotlin
// read-only example: a tab row driven by an index
val titles = listOf("Chats", "Status", "Calls")
var selected by rememberSaveable { mutableIntStateOf(0) }

PrimaryTabRow(selectedTabIndex = selected) {
    titles.forEachIndexed { index, title ->
        Tab(
            selected = selected == index,
            onClick = { selected = index },
            text = { Text(title, maxLines = 1) },
            // icon = { Icon(Icons.Default.Call, contentDescription = null) },
        )
    }
}

A Tab can have text, an icon, or both. LeadingIconTab puts the icon beside the text instead of above it. Keep tab titles short (one word is best) and limit a fixed row to about four tabs; beyond that, use the scrollable variant or a different navigation pattern. Tabs are not a replacement for the bottom bar: see bottom navigation and nested graphs for top-level destinations.

Pagers

HorizontalPager composes only the pages near the visible one, much like a lazy list, so a pager with 1,000 pages is cheap. You give it a PagerState and a lambda that draws page number page.

Kotlin
// read-only example
val pagerState = rememberPagerState(initialPage = 0, pageCount = { 3 })

HorizontalPager(
    state = pagerState,
    modifier = Modifier.fillMaxSize(),
    key = { page -> page },                 // stable identity per page
) { page ->
    when (page) {
        0 -> ChatsPage()
        1 -> StatusPage()
        else -> CallsPage()
    }
}

pageCount is a lambda because the count can change while the pager is on screen (for example when a list loads). VerticalPager is identical but swipes up and down, which suits full-screen vertical feeds.

Useful parameters of the pager:

  • userScrollEnabled = false turns off swiping, for a wizard where only the Next button moves forward.
  • beyondViewportPageCount keeps extra pages composed on each side so they are ready before the user arrives. The default is 0; raise it for pages that are slow to build.
  • contentPadding and pageSpacing add space around and between pages.
  • flingBehavior changes how far a swipe carries (PagerDefaults.flingBehavior lets you snap by more than one page).
  • reverseLayout flips the direction, and Compose also mirrors the pager automatically in right-to-left languages.

Syncing tabs and pager

The rule is simple: PagerState is the single source of truth. The selected tab is derived from pagerState.currentPage, and a tab click asks the pager to scroll. Do not keep a second selected variable, or the two will drift apart.

Kotlin
// read-only example: the standard tabs + pager screen
@Composable
fun InboxScreen() {
    val titles = listOf("Chats", "Status", "Calls")
    val pagerState = rememberPagerState(pageCount = { titles.size })
    val scope = rememberCoroutineScope()

    Column(Modifier.fillMaxSize()) {
        PrimaryTabRow(selectedTabIndex = pagerState.currentPage) {
            titles.forEachIndexed { index, title ->
                Tab(
                    selected = pagerState.currentPage == index,
                    onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                    text = { Text(title) },
                )
            }
        }
        HorizontalPager(state = pagerState, modifier = Modifier.weight(1f)) { page ->
            Text("Content of ${titles[page]}", Modifier.padding(16.dp))
        }
    }
}

Swiping updates currentPage, so the tabs follow without extra code. Tapping a tab launches animateScrollToPage in a coroutine (see coroutines on Android); use scrollToPage for an instant jump. Both are suspend functions, which is why the click handler needs a scope from rememberCoroutineScope.

Which page counts as "current" while a swipe is in progress? That is the part that surprises people, and the stand-in below models it. The pager exposes these values:

  • currentPage: the page that is closest to the snap position. It flips to the next page once more than half of it is visible, while the finger is still moving.
  • settledPage: updates only when scrolling has stopped. Use it for "load data when the user arrives".
  • targetPage: where the pager is heading, which is different from currentPage during a fling or an animated scroll.
  • currentPageOffsetFraction: how far the current page is displaced from perfectly centered, between about -0.5 and 0.5.
Kotlin PagerState during a swipe (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that currentPage changed to 1 at 55% while settledPage stayed at 0 until the finger lifted. If you start a network request on every currentPage change, a slow swipe back and forth fires several. Use settledPage, or snapshotFlow { pagerState.settledPage } inside a LaunchedEffect (see side effects).

Page indicators

Compose has no built-in dot indicator, but it takes a few lines. Draw one dot per page and highlight the one at currentPage. To animate smoothly while swiping, combine currentPage with currentPageOffsetFraction, so the highlight slides between dots.

Kotlin
// read-only example: simple dots
@Composable
fun PageDots(pagerState: PagerState, modifier: Modifier = Modifier) {
    Row(modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        repeat(pagerState.pageCount) { index ->
            val selected = pagerState.currentPage == index
            val size by animateDpAsState(if (selected) 12.dp else 8.dp, label = "dot")
            Box(
                Modifier
                    .size(size)
                    .background(
                        if (selected) MaterialTheme.colorScheme.primary
                        else MaterialTheme.colorScheme.outlineVariant,
                        CircleShape,
                    )
            )
        }
    }
}

For a fractional effect, compute how close each dot is to the pager position: distance = abs((currentPage - index) + currentPageOffsetFraction), and scale the dot by 1 - distance.coerceIn(0f, 1f). The same distance trick drives carousel effects: apply graphicsLayer with an alpha or scale that depends on that distance to fade and shrink neighbors (see animation and modifiers).

The second stand-in computes dot sizes from the pager position with that formula and prints them as an ASCII indicator.

Kotlin Dot sizes from page offset (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Page size and peeking pages

By default a page fills the pager. To show part of the neighboring pages, a "peek" that hints at more content, use contentPadding or a smaller pageSize:

Kotlin
// read-only example: a card carousel that peeks 32.dp on each side
HorizontalPager(
    state = pagerState,
    contentPadding = PaddingValues(horizontal = 32.dp),
    pageSpacing = 12.dp,
) { page -> PosterCard(movies[page]) }

// read-only example: several pages visible at once
HorizontalPager(
    state = pagerState,
    pageSize = PageSize.Fixed(160.dp),     // every page is 160.dp wide
)

PageSize.Fill is the default, PageSize.Fixed(size) gives every page the same width, and you can implement PageSize yourself to compute the size from the viewport (for example "three pages per screen on tablets", see adaptive layouts). Pair a fixed page size with a snapping fling behavior for a carousel that settles on whole items.

Practical advice

  • Per-tab state. A page leaves composition when it scrolls far away, so its remember state is lost. Hoist scroll positions and form data into the ViewModel (see state hoisting), or use rememberSaveable and rememberLazyListState inside the page, which survive recomposition when keyed correctly.
  • One ViewModel for the screen. Let the screen's ViewModel supply data for all tabs unless each tab is a full destination.
  • Accessibility. TalkBack users select tabs by double tap; make sure each tab has readable text. Swipe gestures alone are not enough, which is why tapping a tab must work too.
  • Do not nest same-direction scrolling. A horizontal pager inside a horizontal scroller fights over gestures. A vertical list inside a horizontal pager is fine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How should the selected tab be determined in a tabs + pager screen?

    Tab rows and pagers are independent. Deriving the selection from PagerState keeps swiping and tapping in agreement without a second variable.
  2. 2. Which PagerState value is best for starting a data load when the user has arrived on a page?

    currentPage flips when a page is more than half visible, even while the finger is down. settledPage changes only after the pager has come to rest.
  3. 3. Why does tapping a tab call animateScrollToPage inside scope.launch?

    Scrolling animations suspend until they finish, so you call them from a coroutine scope obtained with rememberCoroutineScope.
  4. 4. How do you make neighboring pages peek in from the sides of a HorizontalPager?

    Padding around the pages leaves room for the next and previous pages to show. PageSize.Fixed does the same by making each page narrower than the viewport.

Summary

  • Use PrimaryTabRow (or the scrollable variant for many tabs) for the tabs and HorizontalPager or VerticalPager for the content; they are linked only by your code.
  • Make PagerState the single source of truth: tabs read currentPage, tab clicks call animateScrollToPage from a coroutine.
  • currentPage changes mid-swipe, settledPage after the swipe, targetPage is the destination, and currentPageOffsetFraction drives animated indicators and carousel effects.
  • pageCount is a lambda, key gives pages stable identity, and beyondViewportPageCount pre-composes neighbors.
  • Peek with contentPadding, size pages with PageSize.Fixed, and keep per-page state in a ViewModel.

Next: Charts and Graphs