Horizo​​ntalPager 检测滑动偏移

HorizontalPager detect swipe offset

我有一个 HorizontalPager 有 3 个项目。

我需要根据用户的滑动知道准确的偏移量

HorizontalPager(
            count = 3
        ) {
            Image(
                painter = painterResource(id = R.drawable.ic_launcher_foreground),
                contentDescription = ""
            )
        }

在 Compose 中,许多视图都有一些状态参数,您可以使用它来检查其状态。

如果是寻呼机,状态有 currentPagecurrentPageOffset 信息。要计算最终偏移量,您还需要使用 Modifier.onSizeChangedBoxWithConstraints.

检查视图大小

我正在使用 derivedStateOf 来防止冗余重组。

val pagerState = rememberPagerState()
val (pagerWidth, setPagerWidth) = remember { mutableStateOf<Int?>(null) }
val scrollOffset by remember(pagerWidth) {
    derivedStateOf {
        if (pagerWidth == null) return@derivedStateOf 0f
        (pagerState.currentPage + pagerState.currentPageOffset) * pagerWidth
    }
}
HorizontalPager(
    state = pagerState,
    count = 3,
    modifier = Modifier
        .onSizeChanged {
            setPagerWidth(it.width)
        }
) {
    Image(
        painter = painterResource(id = R.drawable.ic_launcher_foreground),
        contentDescription = ""
    )
}
Image(
    painter = painterResource(id = R.drawable.ic_launcher_foreground),
    contentDescription = "",
    modifier = Modifier
        .fillMaxWidth()
        .offset(x = with(LocalDensity.current) { -scrollOffset.toDp() })
)