Untitled

 avatar
unknown
kotlin
2 years ago
2.1 kB
8
Indexable
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun PillIndicatorTabRow(
    tabs: List<String>,
    selectedTabIndex: Int,
    updateSelectedTab: (Int) -> Unit
) {
    var anyTabFocused by remember { mutableStateOf(false) }

    TabRow(
        selectedTabIndex = selectedTabIndex,
        separator = { Spacer(modifier = Modifier.width(12.dp)) },
        modifier = Modifier
            .padding(10.dp)
            .onFocusChanged { anyTabFocused = it.hasFocus }
        ,
        indicator = { tabPositions ->
            tabPositions.getOrNull(selectedTabIndex)?.let {
                MyPillIndicator(anyTabFocused = anyTabFocused, currentTabPosition = it)
            }
        }
    ) {
        tabs.forEachIndexed { index, tab ->
            Tab(
                selected = index == selectedTabIndex,
                onFocus = { updateSelectedTab(index) },
            ) {
                Text(
                    text = tab,
                    fontSize = 12.sp,
                    color = LocalContentColor.current,
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp)
                )
            }
        }
    }
}

@Composable
fun MyPillIndicator(
    anyTabFocused: Boolean,
    currentTabPosition: DpRect,
    modifier: Modifier = Modifier,
    activeColor: Color = Color(0xFFE5E1E6),
    inactiveColor: Color = Color(0xFF484362).copy(alpha = 0.4f)
) {
    val width by animateDpAsState(targetValue = currentTabPosition.width)
    val height = currentTabPosition.height
    val leftOffset by animateDpAsState(targetValue = currentTabPosition.left)
    val topOffset = currentTabPosition.top

    val pillColor by
    animateColorAsState(targetValue = if (anyTabFocused) activeColor else inactiveColor)

    Box(
        modifier
            .fillMaxWidth()
            .wrapContentSize(Alignment.BottomStart)
            .offset(x = leftOffset, y = topOffset)
            .width(width)
            .height(height)
            .background(color = pillColor, shape = RoundedCornerShape(50))
            .zIndex(-1f)
            .shadow(2.dp, RoundedCornerShape(50))
    )
}
Editor is loading...