You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TabRow指示器与HorizontalPager滚动偏移同步?官方是否有等效方案?

官方Compose的等效方案说明

官方Compose已内置实现TabRow指示器与HorizontalPager滚动偏移同步的能力,无需依赖Accompanist的工具。具体实现步骤如下:

  • 通过HorizontalPager的PageState获取当前页面的滚动偏移比例
  • 将该偏移量传入TabRow的indicator参数,自定义指示器的位置计算逻辑

示例代码:

val pagerState = rememberPagerState()
TabRow(
    selectedTabIndex = pagerState.currentPage,
    indicator = { tabPositions ->
        val currentTab = tabPositions[pagerState.currentPage]
        val nextTab = tabPositions.getOrNull(pagerState.currentPage + 1)
        val offset = pagerState.currentPageOffsetFraction

        val indicatorStart = if (offset > 0 && nextTab != null) {
            lerp(currentTab.left, nextTab.left, offset)
        } else {
            currentTab.left
        }
        val indicatorEnd = if (offset > 0 && nextTab != null) {
            lerp(currentTab.right, nextTab.right, offset)
        } else {
            currentTab.right
        }

        Box(
            Modifier
                .fillMaxHeight()
                .wrapContentSize(align = Alignment.BottomStart)
                .offset(x = indicatorStart)
                .width(indicatorEnd - indicatorStart)
                .padding(2.dp)
                .background(Color.Blue, RoundedCornerShape(4.dp))
        )
    }
) {
    // 自定义Tab项
}

HorizontalPager(state = pagerState, count = tabCount) { page ->
    // 页面内容
}

利用pagerState.currentPageOffsetFraction获取滚动偏移比例,结合lerp线性插值计算指示器的起始、结束位置,即可实现指示器随HorizontalPager滚动逐像素偏移的效果,和Accompanist的对应工具功能完全等效。

内容的提问来源于stack exchange,提问作者urSus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:54:53