gaugeinvariante
gaugeinvariante

Reputation: 175

Jetpack Compose pointerInput detectTapGestures Set onLongPress timeout?

To implement a Long Press feature on a button or a composable in general the way is to use the Tap Gestures detected in the modifier pointerinput

the code seems pretty straightforward and it works.

Box(modifier = modifier.pointerInput(Unit) {

    detectTapGestures(
        onPress = {
            //Do something
        },
        onDoubleTap = {
           
        },
        onLongPress = {
            onLongClick()
        },
        onTap = {

        }
    )
}

But what I need is to modify the timeout in milliseconds before a longpress event is detected (if the box is pressed for a time of tomeoutMillisec then a longPress event is fired)

The pointerInput scope has the 'val viewConfiguration' (ViewConfiguration is an Interface) that contains the val 'longPressTimeoutMillis'. But I cannot reassign those values (not the longPressTimeoutMillis, not reassign the class viewConfiguration) because they are val and not var

Box(modifier = modifier.pointerInput(Unit) {

    //this gives an error
    this.viewConfiguration.longPressTimeoutMillis  = 200L
    
    detectTapGestures(
        onPress = {
 
        },
        onDoubleTap = {
            
        },
        onLongPress = {
            onLongClick()
        },
        onTap = {

        }
    )
},
  

Anyone knows how to do it?

Upvotes: 2

Views: 2563

Answers (1)

adeous
adeous

Reputation: 143

The question is from a month ago but if others need it. You need to give a new ViewConfiguration in the CompositionLocalProvider that will then wrap your content.

You can put the whole thing in a composable method like below:

    @Composable
    fun UpdateViewConfiguration(
        longPressTimeoutMillis: Long? = null,
        doubleTapTimeoutMillis: Long? = null,
        doubleTapMinTimeMillis: Long? = null,
        touchSlop: Float? = null,
        content: @Composable () -> Unit
) {
        fun ViewConfiguration.updateViewConfiguration() = object : ViewConfiguration {
            override val longPressTimeoutMillis
        get() = longPressTimeoutMillis ?: [email protected]

            override val doubleTapTimeoutMillis
        get() = doubleTapTimeoutMillis ?: [email protected]

            override val doubleTapMinTimeMillis
        get() =
            doubleTapMinTimeMillis ?: [email protected]

            override val touchSlop: Float
        get() = touchSlop ?: [email protected]
        }

        CompositionLocalProvider(
            LocalViewConfiguration provides LocalViewConfiguration.current.updateViewConfiguration()
        ) {
            content()
        }
    }

and thento modidy the

    UpdateViewConfiguration(
        longPressTimeoutMillis = 200L
    ) {
        [... Your content composable ...]
    }

Upvotes: 11

Related Questions