Home > Enterprise >  How to detect swipe in HorizontalPager() in Jetpack compose?
How to detect swipe in HorizontalPager() in Jetpack compose?

Time:11-27

How I can detect when user swiped from one tab to second and etc. in my 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 -> { }
                                    }
                                }
                            }

CodePudding user response:

In your viewmodel, create a pagerState and monitor its currentPage:

class MyViewModel : ViewModel() {

    val pagerState = PagerState()

    init {
        viewModelScope.launch {
            snapshotFlow { pagerState.currentPage }.collect { page ->
                // Page is the index of the page being swiped.
            }
        }
    }
}

In your composable, use the pagerState:

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

}
  • Related