androidandroid-jetpack-composeandroid-jetpack-compose-gesture

How can I get onTouchEvent in Jetpack Compose?


In normal view, we can have onTouchEvent

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {}
            MotionEvent.ACTION_MOVE -> {}
            MotionEvent.ACTION_UP -> {}
            else -> return false
        }
        invalidate()
        return true
    }

In Jetpack Compose, I can only find we have the tapGestureFilter in the modifier, which only takes the action from the ACTION_UP only.

Modifier
    .tapGestureFilter { Log.d("Track", "Tap ${it.x} | ${it.y}") }
    .doubleTapGestureFilter { Log.d("Track", "DoubleTap ${it.x} | ${it.y}") }

Is there an equivalent onTouchEvent for Jetpack Compose?


Solution

  • We have a separate package for that, which is pretty useful. There are two main extension functions that would be suitable for you:

    If you want to handle and process the event I recommend using pointerInteropFilter which is the analogue of View.onTouchEvent. It's used along with modifier:

    Column(modifier = Modifier.pointerInteropFilter {
        when (it.action) {
            MotionEvent.ACTION_DOWN -> {}
            MotionEvent.ACTION_MOVE -> {}
            MotionEvent.ACTION_UP -> {}
            else ->  false
        }
         true
    })
    

    That will be Compose adjusted code to your specified View.onTouchEvent sample.

    P.S. Don't forget about @ExperimentalPointerInput annotation.