Android Compose Task App Implementation Series: Animated Dynamic Tab Selector

Ken Ruiz Inoue
Deuk
Published in
4 min readMar 9, 2024

Production App

Anothertask Version 1.0.0 is available here if you are interested 😉

Objective

Recreate the Tab Selector UI component from the Taskose UI design kit I acquired, utilizing Android Jetpack Compose. The endeavor will involve crafting smooth tab transition animations, accommodating a flexible number of tabs (between two to four), and showcasing effective state management with a preview component.

Dynamic Tab Selector

Environment

  • Android Studio Iguana | 2023.2.1
  • Compose version: composeBom = "2023.08.00"
  • Pixel 6 API 30 Emulator
  • Project Minimum SDK: 27

Implementation

// Your package

import android.widget.Toast
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun DynamicTabSelector(
tabs: List<String>, // Can be 2 to 4 options
selectedOption: Int = 0,
containerColor: Color = Color(0xFFDFE6EE),
tabColor: Color = Color.White,
selectedOptionColor: Color = Color(0xFF7980FF),
containerCornerRadius: Dp = 16.dp,
tabCornerRadius: Dp = 12.dp,
selectorHeight: Dp = 48.dp,
tabHeight: Dp = 40.dp,
spacing: Dp = 4.dp,
textStyle: TextStyle = TextStyle(
color = Color(0xFF31394F).copy(alpha = 0.6f),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
fontSize = 12.sp
),
selectedTabTextStyle: TextStyle = TextStyle(
color = selectedOptionColor,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
fontSize = 12.sp
),
onTabSelected: (selectedIndex: Int) -> Unit = {}
) {
if (tabs.size !in 2..4) {
throw IllegalArgumentException("DynamicTabSelector must have between 2 and 4 options")
}

// Use BoxWithConstraints to get the width of the container
BoxWithConstraints(
modifier = Modifier
.clip(RoundedCornerShape(containerCornerRadius))
.height(selectorHeight)
.fillMaxSize()
.background(containerColor)
) {
val segmentWidth = maxWidth / tabs.size
// Adjusted width for each tab, accounting for spacing
val boxWidth = segmentWidth - spacing * 2
val positions = tabs.indices.map { index ->
segmentWidth * index + (segmentWidth - boxWidth) / 2
}
// Animate the X offset of the selected tab to smoothly transition between tabs
val animatedOffsetX by animateDpAsState(targetValue = positions[selectedOption], label = "")
// Determine the maximum height available for alignment
val containerHeight = maxHeight
// Center the tab selector vertically within the container
val verticalOffset = (containerHeight - tabHeight) / 2

Row(
modifier = Modifier.fillMaxHeight(),
// Ensures spacing between options
horizontalArrangement = Arrangement.spacedBy(spacing),
verticalAlignment = Alignment.CenterVertically
) {
tabs.forEachIndexed { index, text ->
Text(
text = text,
style = textStyle,
modifier = Modifier
.width(segmentWidth)
.clickable(
indication = null,
// Avoids ripple effect for a cleaner look
interactionSource = remember { MutableInteractionSource() }
) {
// Trigger callback with the index of the selected tab
onTabSelected(index)
}
)
}
}
// Selected tab highlighted by applying the selected tab text style
Box(
modifier = Modifier
// Position the selector dynamically based on the selected tab
.offset(x = animatedOffsetX, y = verticalOffset)
.clip(RoundedCornerShape(tabCornerRadius))
.width(boxWidth) // Updated box width
.height(tabHeight)
.background(tabColor)
) {
Text(
text = tabs[selectedOption], // Use the selected option's text
modifier = Modifier.align(Alignment.Center),
style = selectedTabTextStyle
)
}
}
}

@Preview
@Composable
fun DynamicTabSelectorPreview() {
/**
* This preview demonstrates the use of remember { mutableStateOf(0) } to maintain the
* selected tab's state across recompositions in DynamicTabSelector, enabling dynamic
* UI updates in Jetpack Compose.
**/
val selectedOption = remember { mutableIntStateOf(0) }
val optionTexts = listOf("Tab 1", "Tab 2", "Tab 3")
val context = LocalContext.current
Box(
modifier = Modifier
.background(Color.Gray)
.fillMaxSize()
.padding(24.dp),
contentAlignment = Alignment.Center
) {
DynamicTabSelector(tabs = optionTexts, selectedOption = selectedOption.intValue) {
Toast.makeText(context, "Selected tab: ${it + 1}", Toast.LENGTH_SHORT).show()
selectedOption.intValue = it
}
}
}

Preview Result

Explore More

For developers eager to deepen their understanding or explore more about modern Android development, a wealth of resources and guides await.

If you’ve found this resource helpful, consider sharing your support through claps or a follow, and stay tuned for more insights into the evolving landscape of Android development. See you the next time!

Deuk Services: Your Gateway to Leading Android Innovation

Are you looking to boost your business with top-tier Android solutions?Partner with Deuk services and take your projects to unparalleled heights.

🚀 Boost Your Productivity with Notion

New to Notion? Discover how it can revolutionize your productivity

Ready to take your productivity to the next level? Integrate this content into your Notion workspace with ease:

1 Access the Notion Version of this Content

2 Look for the Duplicate button at the top-right corner of the page

3 Click on it to add this valuable resource to your Notion workspace

Seamlessly integrate this guide into your Notion workspace for easy access and swift reference. Leverage Notion AI to search and extract crucial insights, enhancing your productivity. Start curating your knowledge hub with Notion AI today and maximize every learning moment.

--

--