如何让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
相关产品推荐
相关产品推荐

