如何在 Jetpack compose 中检测 Horizo​​ntalPager 中的滑动?

Waf*_*_ck 4 android android-layout kotlin android-jetpack android-jetpack-compose

我如何检测用户何时从一个选项卡滑动到第二个选项卡等HorizontalPager()?

val pagerState = rememberPagerState(initialPage = 0)
HorizontalPager(count = TabCategory.values().size, state = pagerState) { index ->
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.onBackground)
    ) {
        when (TabCategory.values()[index]) {
            TabCategory.Opinion -> { }
            TabCategory.Information -> { }
            TabCategory.Videos -> { }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*Dev 9

在您的视图模型中,创建一个 pagerState 并监视其 currentPage:

class MyViewModel : ViewModel() {

    val pagerState = PagerState()

    init {
        viewModelScope.launch {
            snapshotFlow { pagerState.currentPage }.collect { page ->
                // Page is the index of the page being swiped.
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的可组合项中,使用 pagerState:

HorizontalPager(
  state = myViewModel.pagerState,
) { page ->

}
Run Code Online (Sandbox Code Playgroud)

  • 这将在点击和滑动选项卡上触发。 (2认同)