Search code examples
androidkotlinandroid-layoutandroid-jetpack-composeandroid-jetpack

How to detect swipe in HorizontalPager in Jetpack compose?


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 -> { }
        }
    }
}

Solution

  • 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 ->
    
    }