[英]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()?
如何在我的 HorizontalPager
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 -> { }
}
}
}
In your viewmodel, pass the pagerState to the HorizontalPager:在您的视图模型中,将 pagerState 传递给 HorizontalPager:
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:在您的可组合中,使用 pagerState:
HorizontalPager(
state = myViewModel.pagerState,
) { page ->
}
A PagerState
has an InteractionSource
that keeps track of that stuff. PagerState
有一个跟踪这些内容的InteractionSource
。 The method collectIsDraggedAsState
returns a State<Boolean>
you can subscribe to that exposes its current value via .value
. collectIsDraggedAsState
方法返回一个您可以订阅的State<Boolean>
,它通过.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()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.