Jetpack Compose 手勢(shì)Modifier.pointerInput 手勢(shì)檢測(cè)器
Modifier.pointerInput 是手勢(shì)檢測(cè)器,先來(lái)看看Modifier.pointerInput的代碼
fun Modifier.pointerInput(
? ? block: suspend PointerInputScope.() -> Unit
){...}
block 是PointerInputScope。PointerInputScope主要有如下幾個(gè)擴(kuò)展方法跟一個(gè)內(nèi)部方法awaitPointerEventScope:
detectTapGestures 可以監(jiān)聽(tīng)長(zhǎng)按,點(diǎn)擊,雙擊,按下
detectDragGestures 可以監(jiān)聽(tīng)拖動(dòng)。
detectHorizontalDragGestures 可以監(jiān)聽(tīng)水平方向時(shí)候的拖動(dòng)
detectVerticalDragGestures 可以監(jiān)聽(tīng)豎直方向時(shí)候的拖動(dòng)
detectDragGesturesAfterLongPress 可以監(jiān)聽(tīng)長(zhǎng)按之后的拖動(dòng)
detectTransformGestures 檢測(cè)平移,縮放,旋轉(zhuǎn)的
forEachGesture 遍歷每組事件。
awaitPointerEventScope?
forEachGesture(反復(fù)的處理手勢(shì))
forEachGesture是反復(fù)的處理手勢(shì)。接下來(lái),我們先來(lái)看看forEachGesture的代碼
suspend fun PointerInputScope.forEachGesture(block: suspend PointerInputScope.() -> Unit) {...}
block 是一個(gè)PointerInputScope。也就是說(shuō)forEachGesture里面可以使用PointerInputScope的所有的方法。 forEachGesture是反復(fù)的處理手勢(shì)是什么意思呢? 舉個(gè)例子:
@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))
}
上面的代碼,當(dāng)我們?cè)贑olumn上滑動(dòng)的時(shí)候,會(huì)打出來(lái)awaitFirstDown以及onDrag的log。但是當(dāng)我們抬起手指之后再重新按下去對(duì)Column進(jìn)行滑動(dòng),發(fā)現(xiàn)不打log了。也就是說(shuō)這時(shí)候的手勢(shì)監(jiān)聽(tīng)只有一次。如果我們想要去反復(fù)的監(jiān)聽(tīng)該手勢(shì)。我們就可以添加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))
}
這時(shí)候我們?cè)偃グ聪翪olumn并且滑動(dòng),會(huì)發(fā)現(xiàn)打出來(lái)log。抬起手指,重新按下滑動(dòng)還是會(huì)打出log。這個(gè)就是forEachGesture的作用。
作者:Bug小明
鏈接:https://juejin.cn/post/6975041659729870885
來(lái)源:稀土掘金
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。