androidandroid-jetpackandroid-jetpack-compose

ScrollableTabRow indicator width to match text inside Tab


My problem is that i need a tab indicator to match exactly to the text that is above it (from designs):

proper

However, all i managed to do is get something looking like this:

improper

My code:

 ScrollableTabRow(
            selectedTabIndex = selectedSeason,
            backgroundColor = Color.White,
            edgePadding = 0.dp,
            modifier = Modifier
                .padding(vertical = 24.dp)
                .height(40.dp),
            indicator = { tabPositions ->
                TabDefaults.Indicator(
                    color = Color.Red,
                    height = 4.dp,
                    modifier = Modifier
                        .tabIndicatorOffset(tabPositions[selectedSeason])
                )
            }
        ) {
            item.seasonList().forEachIndexed { index, contentItem ->
                Tab(
                    modifier = Modifier.padding(bottom = 10.dp),
                    selected = index == selectedSeason,
                    onClick = { selectedSeason = index }
                )
                {
                    Text(
                        "Season " + contentItem.seasonNumber(),
                        color = Color.Black,
                        style = styles.seasonBarTextStyle(index == selectedSeason)
                    )
                }
            }

        }
    }

Also a little bonus question, my code for this screen is inside lazy column, now i need to have this tab row to behave somewhat like a sticky header(when it gets to the top, screen stops scrolling, but i can still scroll the items inside it)

Thanks for your help


Solution

  • Have a look at the provided modifier, it internally computes a width value. If you change the Modifier yourself to the code below you can provide a width value.

    fun Modifier.ownTabIndicatorOffset(
        currentTabPosition: TabPosition,
        currentTabWidth: Dp = currentTabPosition.width
    ): Modifier = composed(
        inspectorInfo = debugInspectorInfo {
            name = "tabIndicatorOffset"
            value = currentTabPosition
        }
    ) {
        val indicatorOffset by animateAsState(
            targetValue = currentTabPosition.left,
            animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing)
        )
        fillMaxWidth()
            .wrapContentSize(Alignment.BottomStart)
            .offset(x = indicatorOffset + ((currentTabPosition.width - currentTabWidth) / 2))
            .preferredWidth(currentTabWidth)
    }
    

    Now to the point of how to get the width of your Text: Warning: I think it's not the way to do it but I can't figure out a better one atm.

    At first, I create a Composable to provide me the width of its contents.

    @Composable
    fun MeasureWidthOf(setWidth: (Int) -> Unit, content: @Composable () -> Unit) {
        Layout(
            content = content
        ) { list: List<Measurable>, constraints: Constraints ->
            check(list.size == 1)
            val placeable = list.last().measure(constraints)
            layout(
                width = placeable.width.also(setWidth),
                height = placeable.height
            ) {
                placeable.placeRelative(x = 0, y = 0)
            }
        }
    }
    

    Now I can use it in your example (simplified):

    // Needed for Android
    fun Float.asPxtoDP(density: Float): Dp {
        return (this / (density)).dp
    }
    
    fun main(args: Array<String>) {
        Window(size = IntSize(600, 800)) {
            val (selectedSeason, setSelectedSeason) = remember { mutableStateOf(0) }
            val seasonsList = mutableListOf(2020, 2021, 2022)
            val textWidth = remember { mutableStateListOf(0, 0, 0) }
            // Android
            val density = AmbientDensity.current.density
            ScrollableTabRow(
                selectedTabIndex = selectedSeason,
                backgroundColor = Color.White,
                edgePadding = 0.dp,
                modifier = Modifier
                    .padding(vertical = 24.dp)
                    .height(40.dp),
                indicator = { tabPositions ->
                    TabDefaults.Indicator(
                        color = Color.Red,
                        height = 4.dp,
                        modifier = Modifier
                            .ownTabIndicatorOffset(
                                currentTabPosition = tabPositions[selectedSeason],
                                // Android:
                                currentTabWidth = textWidth[selectedSeason].asPxtoDP(density)
                               // Desktop:
                               currentTabWidth = textWidth[selectedSeason].dp
                            )
                    )
                }
            ) {
                seasonsList.forEachIndexed { index, contentItem ->
                    Tab(
                        modifier = Modifier.padding(bottom = 10.dp),
                        selected = index == selectedSeason,
                        onClick = { setSelectedSeason(index) }
                    )
                    {
                        val text = @Composable {
                            Text(
                                text = "Season $contentItem",
                                color = Color.Black,
                                textAlign = TextAlign.Center
                            )
                        }
                        if (index == selectedSeason) {
                            MeasureWidthOf(setWidth = { textWidth[index] = it }) {
                                text()
                            }
                        } else {
                            text()
                        }
                    }
                }
            }
        }
    }
    

    Edit (05.01.2021): Simplified Modifier code

    Edit (09.01.2021): Fixed density problem on android and tested on Desktop and Android