How to detect swipe in HorizontalPager in Jetpack compose?

Viewed 986

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

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

}

A PagerState has an InteractionSource that keeps track of that stuff. The method collectIsDraggedAsState returns a State<Boolean> you can subscribe to that exposes its current value via .value.

This seems to be testing well.

@Composable
fun ExampleComposable(){
    val pagerState=rememberPagerState()
    val isDragged=pagerState.interactionSource.collectIsDraggedAsState()
    HorizontalPager(count = injector.snippets.size,
    state = pagerState,
    ){index->
         MyFancyExampleComposable(index)
         if (isDragged.value){
              respondToPageSwipeOrPartialPageSwipe()
            }

     }
}
Related