我们如何将选项卡布局的“选项卡指示器”移至“jetpack compose”中的顶部?默认情况下,它出现在所选选项卡的底部

Hel*_*Joy 2 android android-jetpack-compose

TabRow(
                selectedTabIndex = tabIndex,
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(),
                indicator = {tabPositions-> 
                    Box(
                        modifier = Modifier
                            .tabIndicatorOffset(tabPositions[tabIndex])
                            .height(indicatorSize)
                            .background(color = indicatorColor)
                    )
                }
            ) 
Run Code Online (Sandbox Code Playgroud)

我们可以在指示器中添加任何内容以将其移至顶部吗?我在 jetpack compose 中看不到与此“app:tabIndicatorGravity”类似的内容。

Gab*_*tti 6

没有参数可以做到这一点。

这是一个解决方法。
目前选项卡高度定义为

private val SmallTabHeight = 48.dp.   //only text
private val LargeTabHeight = 72.dp.   //text + icon
Run Code Online (Sandbox Code Playgroud)

您可以定义自己的指标并应用偏移量:

@Composable
fun TopIndicator(color: Color, modifier: Modifier = Modifier) {
    Box(
        modifier
            .fillMaxWidth()
            .offset(y= (-46).dp)  //SmallTabHeight=48.dp - height indicator=2.dp
            .height(2.dp)
            .background(color = color)
    )
}
Run Code Online (Sandbox Code Playgroud)

并在您的代码中:

// Reuse the default offset animation modifier, but use our own indicator
val indicator = @Composable { tabPositions: List<TabPosition> ->
    TopIndicator(Color.White, Modifier.tabIndicatorOffset(tabPositions[state]))
}

TabRow(
        selectedTabIndex = state,
        indicator = indicator
){
        //...
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述