Tabs (TabLayout) in Jetpack Compose

Burak
ITNEXT
Published in
3 min readDec 11, 2022

--

Tabs are useful for switching between views of distinct and related groups of information. Tabs organize content across different screens, data sets, and other interactions.

Table of Contents

Getting Started

We’ll need two accompanist dependencies. You can check the latest version from here.

def accompanist_version = "0.28.0"
implementation "com.google.accompanist:accompanist-pager:$accompanist_version" // Pager
implementation "com.google.accompanist:accompanist-pager-indicators:$accompanist_version" // Pager Indicators

Preparations

Before we implement Tabs, we’ll create data class and screens.

data class TabRowItem(
val title: String,
val icon: ImageVector,
val screen: @Composable () -> Unit,
)

This data class can be changed depending on the requirements. You can remove either title or icon but at least one of them should remain.

This will be used for our examples. You can and should change it later.

Finally, let’s create tabs list.

val tabRowItems = listOf(
TabRowItem(
title = "Tab 1",
screen = { TabScreen(text = "Tab 1") },
icon = Icons.Rounded.Place,
),
TabRowItem(
title = "Tab 2",
screen = { TabScreen(text = "Tab 2") },
icon = Icons.Rounded.Search,
),
TabRowItem(
title = "Tab 3",
screen = { TabScreen(text = "Tab 3") },
icon = Icons.Rounded.Star,
)
)

That’s it for preparations section.

Implementation

val pagerState = rememberPagerState()
val coroutineScope = rememberCoroutineScope()

pagerStatewill be necessary to remember & keep the state of the pager.

coroutineScope will be used for pagerState scrolling.

We first add TabRow which will be the container for Tab.

selectedTabIndex, the index of the currently selected tab.

indicator, that represents which tab is currently selected.

Inside of the TabRow we will create Tab. Since we’ve already created tabs list, we’ll simply call tabRowItems.forEachIndex and set Tabs.

selected, whether this tab is selected or not.

icon and text are optional. You can either select one of them or both, like our example.

In onClick method, we launch the coroutineScope and call animateScrollToPage function. It simply animates to the given page to the middle of the viewport.

HorizontalPagerA horizontally scrolling layout that allows users to flip between items to the left and right.

Finally, we’ll add HorizontalPager. count is the number of pages and state is the object to be used to control or observe the pager’s state which we’ve already created above.

Inside of the HorizontalPager, we’ll get current page and call screen which again we’ve already created in our custom data class.

Full code,

Tabs GIF

That’s it! I hope it was useful. 👋👋

Sources:

You can contact me on,

--

--