为什么Horizo​​ntalPager的自动滚动在手动滚动后就停止了?

Moh*_*qer 6 kotlin android-jetpack-compose jetpack-compose-accompanist

我有一个HorizontalPager

val pageCount = bannerList.size
val startIndex = Int.MAX_VALUE / 2
val pagerState = rememberPagerState(initialPage = 100)
HorizontalPager(
    count = Int.MAX_VALUE,
    state = pagerState,
    contentPadding = PaddingValues(
        horizontal = 20.dp
    ),
    modifier = Modifier
        .fillMaxWidth()
) { index ->
// content goes here
}
Run Code Online (Sandbox Code Playgroud)

我让它像横幅一样每 4 秒滚动一次LaunchedEffect

LaunchedEffect(
    key1 = Unit,
    block = {
        repeat(
            times = Int.MAX_VALUE,
            action = {
                delay(
                    timeMillis = 4000
                )
                pagerState.animateScrollToPage(
                    page = pagerState.currentPage + 1
                )
            }
        )
    })
Run Code Online (Sandbox Code Playgroud)

它每 4 秒滚动一次,但当我手动滚动时,它HorizontalPager会停止滚动!

有什么建议如何解决这个问题吗?

Phi*_*hov 11

animateScrollToPage手动滚动期间调用时抛出异常:

java.util.concurrent.CancellationException: Current mutation had a higher priority
Run Code Online (Sandbox Code Playgroud)

您可以通过多种方式解决它。例如,捕获异常并忽略它:

delay(
    timeMillis = 4000
)
try {
    pagerState.animateScrollToPage(
        page = pagerState.currentPage + 1
    )
} catch (_: Throwable) {
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是检查寻呼机是否被拖动并LaunchedEffect在这段时间内停止:

val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
if (!isDragged) {
    LaunchedEffect(Unit) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为第二种解决方案更干净,因为在这种情况下,计时器将重新启动,并延迟到下一个滚动将始终相同。