Jetpack Compose 手势Modifier.pointerInput 手势检测器
Modifier.pointerInput 是手势检测器,先来看看Modifier.pointerInput的代码
fun Modifier.pointerInput(
block: suspend PointerInputScope.() -> Unit
){...}
block 是PointerInputScope。PointerInputScope主要有如下几个扩展方法跟一个内部方法awaitPointerEventScope:
detectTapGestures 可以监听长按,点击,双击,按下
detectDragGestures 可以监听拖动。
detectHorizontalDragGestures 可以监听水平方向时候的拖动
detectVerticalDragGestures 可以监听竖直方向时候的拖动
detectDragGesturesAfterLongPress 可以监听长按之后的拖动
detectTransformGestures 检测平移,缩放,旋转的
forEachGesture 遍历每组事件。
awaitPointerEventScope
forEachGesture(反复的处理手势)
forEachGesture是反复的处理手势。接下来,我们先来看看forEachGesture的代码
suspend fun PointerInputScope.forEachGesture(block: suspend PointerInputScope.() -> Unit) {...}
block 是一个PointerInputScope。也就是说forEachGesture里面可以使用PointerInputScope的所有的方法。 forEachGesture是反复的处理手势是什么意思呢? 举个例子:
@Preview
@Composable
fun test(){
Column(modifier = Modifier.pointerInput(Unit) {
awaitPointerEventScope {
val id = awaitFirstDown().id
Log.e("ccm","==awaitFirstDown==id===${id}===")
drag(id,onDrag = {
Log.e("ccm==onDrag=","====id===${it.id}===position===${it.position}===changedToUp===${it.changedToUp()}==changeToDown==${it.changedToUp()}")
})
}
}.fillMaxSize().background(Color.Red))
}
上面的代码,当我们在Column上滑动的时候,会打出来awaitFirstDown以及onDrag的log。但是当我们抬起手指之后再重新按下去对Column进行滑动,发现不打log了。也就是说这时候的手势监听只有一次。如果我们想要去反复的监听该手势。我们就可以添加forEachGesture。代码修改如下:
@Preview
@Composable
fun forEachGestureTest(){
Column(modifier = Modifier.pointerInput(Unit) {
forEachGesture {
awaitPointerEventScope {
val id = awaitFirstDown().id
Log.e("ccm","==awaitFirstDown==id===${id}===")
drag(id,onDrag = {
Log.e("ccm==onDrag=","====id===${it.id}===position===${it.position}===")
})
}
}
}.fillMaxSize().background(Color.Red))
}
这时候我们再去按下Column并且滑动,会发现打出来log。抬起手指,重新按下滑动还是会打出log。这个就是forEachGesture的作用。
作者:Bug小明
链接:https://juejin.cn/post/6975041659729870885
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。