Kotlin with Jetpack Compose -Tabs

Maneesha Erandi
5 min readMay 31

Using Tabs to navigate between screens allows users to interact with the app in an easy and organized way.

We can create a Tab bar with Jetpack Compose very easily. We can use TabRow and Tab composable to create a tab bar with the custom content we need. Let’s check out these components.

TabRow component with parameters

@Composable
@UiComposable
fun TabRow(
selectedTabIndex: Int,
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
indicator: @Composable @UiComposable
(tabPositions: List<TabPosition>) -> Unit = @Composable { tabPositions ->
TabRowDefaults.Indicator(
Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
)
},
divider: @Composable @UiComposable () -> Unit =
@Composable {
TabRowDefaults.Divider()
},
tabs: @Composable @UiComposable () -> Unit
)

We can pass a set of Tabs to the above tabs param.

Tab component with parameters

@Composable
fun Tab(
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
text: @Composable (() -> Unit)? = null,
icon: @Composable (() -> Unit)? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
selectedContentColor: Color = LocalContentColor.current,
unselectedContentColor: Color = selectedContentColor.copy(alpha = ContentAlpha.medium)
)

We can create a tab bar with built-inTabRow and Tab very easily. But if we need to create our own custom tab bar, we can create a fancy tab to display the tab we need.

The same goes with the tab indicator. We can create a custom indicator and pass it to the TabRow.

Let’s create a simple example

Add the libraries to the app levelbuild.gradle file. These are for the horizontal pager and material icons that not included.

    implementation "com.google.accompanist:accompanist-pager:0.25.0"
implementation "com.google.accompanist:accompanist-pager-indicators:0.25.0"
implementation…
Maneesha Erandi

I write about mobile development and wildlife.