Counterpart of onTouchEvent for Jetpack Compose and transform gesture with specific number of pointers

Last update: May 10, 2022

Jetpack Compose Gestures

Counterpart of onTouchEvent for Jetpack Compose and transform gesture with specific number of pointers

gestures.mp4

Modifier.pointerMotionEvents

Creates a modifier for processing pointer motion input within the region of the modified element.

After AwaitPointerEventScope.awaitFirstDown returns a PointerInputChange followed by onDown at first pointer contact. Moving any pointer invokes AwaitPointerEventScope.awaitPointerEvent then onMove is called. When last pointer is up onUp is called.

To prevent other pointer functions that call awaitFirstDown or awaitPointerEvent (scroll, swipe, detect functions) call PointerInputChange.consume() in onDown, and call PointerInputChange.consume() in onMove block.

fun Modifier.pointerMotionEvents(
    vararg keys: Any?,
    onDown: (PointerInputChange) -> Unit = {},
    onMove: (PointerInputChange) -> Unit = {},
    onUp: (PointerInputChange) -> Unit = {},
    delayAfterDownInMillis: Long = 0L
) = this.then(
    Modifier.pointerInput(keys) {
        detectMotionEvents(onDown, onMove, onUp, delayAfterDownInMillis)
    }
)

pointerMotionEventList returns list of pointers in onMove

fun Modifier.pointerMotionEventList(
    key1: Any? = Unit,
    onDown: (PointerInputChange) -> Unit = {},
    onMove: (List<PointerInputChange>) -> Unit = {},
    onUp: (PointerInputChange) -> Unit = {},
    delayAfterDownInMillis: Long = 0L
) 
  • delayAfterDownInMillis parameter invokes Coroutines delay between onDown, and onMove. There is a delay about 20ms between in View's onTouchEvent first touch and move, similar delay might be required with Compose too, especially when drawing to Canvas which misses very fast events, Delaying move behavior might be required to detect whether is touch is in required region of Composable at first pointer contact.

PointerInputChange down and move events should be consumed if you need to prevent other gestures like scroll or other pointerInputs to not intercept your gesture

 Modifier.pointerMotionEvents(
    onDown = {
        // When down is consumed
        it.consume()
    },
    onMove = {
        // Consuming move prevents scroll other events to not get this move event
        it.consume()
    },
    delayAfterDownInMillis = 20
)

You can refer this answer for details.

Modifier.detectTransformGesturesAndChanges

A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the user can use rotation, panning and zoom gestures. onGesture will be called when any of the rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and pan as an offset in pixels. Each of these changes is a difference between the previous call and the current gesture. This will consume all position changes after touch slop has been reached. onGesture will also provide centroid of all the pointers that are down.

After gesture started when last pointer is up onGestureEnd is triggered. pointerList returns info about pointers that are available to this gesture

Usage

Modifier.pointerInput(Unit) {
    detectTransformGesturesAndChanges(
        onGesture = { gestureCentroid: Offset,
                      gesturePan: Offset,
                      gestureZoom: Float,
                      gestureRotate: Float,
                      pointerList: List<PointerInputChange> ->

        },
        onGestureEnd = {
            transformDetailText = "GESTURE END"
        }
    )
}

Modifier.detectPointerTransformGestures

Transform gesture as detectTransformGestures except with gestureEnd callback, returns number of pointers that are down and checks for requisite and number of pointers before continuing transform gestures. when requisite is not met gesture is on hold and ends when last pointer is up. This might be useful in scenarios like not panning when pointer number is higher than 1, or scenarios require specific conditions to be met

Modifier
    .pointerInput(Unit) {
        detectPointerTransformGestures(
            numberOfPointers = 1,
            requisite = PointerRequisite.GreaterThan,
            onGesture = { gestureCentroid: Offset,
                          gesturePan: Offset,
                          gestureZoom: Float,
                          gestureRotate: Float,
                          numberOfPointers: Int ->

            },
            onGestureEnd = {
                transformDetailText = "GESTURE END"
            }
        )
    }

Gesture Tutorial

If you need more detailed tutorial about Jetpack Compose gestures check this tutorial

Gradle Setup

To get a Git project into your build:

  • Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:
allprojects {
  repositories {
      ...
      maven { url 'https://jitpack.io' }
  }
}
  • Step 2. Add the dependency
dependencies {
  implementation 'com.github.SmartToolFactory:Compose-Extended-Gestures:Tag'
}

GitHub

https://github.com/SmartToolFactory/Compose-Extended-Gestures
You might also like...

FirestoreCleanArchitectureApp is an app built with Kotlin and Firestore that displays data in real-time using the MVVM Architecture Pattern. For the UI it uses Jetpack Compose, Android's modern toolkit for building native UI.

FirestoreCleanArchitectureApp is an app built with Kotlin and Firestore that displays data in real-time using the MVVM Architecture Pattern. For the UI it uses Jetpack Compose,  Android's modern toolkit for building native UI.

FirestoreCleanArchitectureApp FirestoreCleanArchitectureApp is an app built with Kotlin and Cloud Firestore that displays data in real-time using Andr

Jun 16, 2022

Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Apr 2, 2022

New style for app design Online Sunglasses Shop App UI made in Jetpack Compose.😉😎

New style for app design Online Sunglasses Shop App UI made in Jetpack Compose.😉😎

JetSunglassUI-Android New style for app design Online Sunglasses Shop App UI made in Jetpack Compose. 😉 😎 (Navigation Components, Dagger-Hilt, Mater

Apr 13, 2022

📚 Sample Android Components Architecture on a modular word focused on the scalability, testability and maintainability written in Kotlin, following best practices using Jetpack.

📚  Sample Android Components Architecture on a modular word focused on the scalability, testability and maintainability written in Kotlin, following best practices using Jetpack.

Android Components Architecture in a Modular Word Android Components Architecture in a Modular Word is a sample project that presents modern, 2020 app

Jun 23, 2022

An Android app built with Kotlin, consuming StarWars API to display characters of the popular StarWars Movie. It is built with the MVVM pattern and the latest Jetpack components.

An Android app built with Kotlin, consuming StarWars API to display characters of the popular StarWars Movie. It is built with the MVVM pattern and the latest Jetpack components.

StarWars An Android app built with Kotlin, consuming StarWars API to display characters of the popular StarWars Movie. It is built with the MVVM patte

Jun 16, 2022

ViewModel-Lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

ViewModel-Lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

ViewModel Lifecycle 🌳 ViewModel Lifecycle allows you to track and observe Jetpa

Jun 19, 2022

Viewmodel-lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

Viewmodel-lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

ViewModel Lifecycle 🌳 ViewModel Lifecycle allows you to track and observe Jetpa

Feb 6, 2022

🗡️ Deddit demonstrates modern Android development with Hilt, Coroutines, Flow, Jetpack, and Material Design based on MVVM architecture

 🗡️ Deddit demonstrates modern Android development with Hilt, Coroutines, Flow, Jetpack, and Material Design based on MVVM architecture

Deddit demonstrates modern Android development with Hilt, Coroutines, Flow, Jetpack (ViewModel,Paging3), and Material Design based on MVVM

Apr 18, 2022
A basic library that enables easy composition of gesture sequence recognition on a view

GestureSequence A basic library that enables easy composition of gesture sequence recognition on a view. Basic API looks like: // Perform action() whe

Feb 23, 2022
A TODO list app with location reminders that remind the user to do something when the user is at a specific location

Project Title Location Reminder Getting Started A TODO list app with location reminders that remind the user to do something when the user is at a spe

Dec 5, 2021
A specific format represent file directory in Json

CascadeJson.kt A specific format represent file directory in Json Provide a function for convert to map or json string in Kotlin Usage Download zip fi

Feb 22, 2022
A Simple Android library to get the number of words and give you the time it will take you to finish an article/story.

MinRead A Simple Android library to get the number of words and give you the time it will take you to finish an article/story. Prerequisite Androidx K

Nov 17, 2021
🪄 This is an animation library with an increasing number of TextViews
🪄 This is an animation library with an increasing number of TextViews

CountNumberEvent ?? This is an animation library with an increasing number of TextViews Demo Setup Add it in your root build.gradle at the end of repo

Feb 17, 2022
Send Whatsapp Message Without Saving Mobile Number

Send Whatsapp Message Without Saving Mobile Number In this project i created the

Apr 22, 2022
FizzBuzzKotlin - A function fizzBuzz to generate a list of string based on the input number

FizzBuzzKotlin write a function fizzBuzz to generate a list of string based on t

Feb 12, 2022
This project aims to provide a solution for finding the right product for a given EAN (European Article Number)

This project aims to provide a solution for finding the right product for a given EAN (European Article Number)

Apr 18, 2022
Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.

Jetpack Compose for Desktop and Web, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.

Jun 25, 2022