jetpack compose ScrollableTabRow Indicator指示器宽度无法设定

375 阅读1分钟

image.png

看代码我们知道

TabRowDefaults.Indicator(
    Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex])
)

用了这个东西然后写死了指示器的宽度按照currentTabPosition.width

image.png

所以解决办法 自己写一个

//指示器的位置和动画
fun Modifier.tabIndicatorOffsetSmall(
    currentTabPosition: TabPosition,
): Modifier = composed(
    inspectorInfo = debugInspectorInfo {
        name = "tabIndicatorOffset"
        value = currentTabPosition
    }
) {
    val indicatorOffset by animateDpAsState(
        targetValue = currentTabPosition.left,
        animationSpec = tween(durationMillis = 250, easing = FastOutSlowInEasing),
        label = "DpAnimation"
    ) {}
    wrapContentSize(Alignment.BottomStart)
        .padding(start = (currentTabPosition.width - 15.dp) / 2)
        .offset(x = indicatorOffset)
        .width(15.dp)//指示器的宽度
        .height(3.dp)
}

然后我们的UI还希望指示器是个圆角的 那么指示器也改造一下

//指示器的样子
@Composable
fun Indicator(modifier: Modifier = Modifier, color: Color = LocalContentColor.current) {
    Surface(
        modifier, color = color, shape = RoundedCornerShape(2.dp)
    ) {}
}

调用

Indicator(modifier = Modifier.tabIndicatorOffsetSmall(tabPositions[tabIndex.value]), color = BgMainTheme )

image.png