How to change touchSlop (or any other property) in ViewConfiguration of current composable in JetpackCompose

Introduction

In this tutorial, I will show you how you can change the ViewConfiguration touchSlop value which is defined as the “Distance in pixels a touch can wander before we think the user is scrolling”. From its definition, you can see that it is sometimes useful to change it to any value other than the default value. For example, if you want to create a drawing feature or if you want to implement a draggable composable without waiting for touch to wander before considering it as a drag gesture.

Code

First, inside your composable function, you need to get the current ViewConfiguration and store it in a variable.

val originalViewConfiguration = LocalViewConfiguration.current
Kotlin

Next, create a new object that implements the ViewConfiguration interface and store it in a variable

val viewConfiguration = object : ViewConfiguration {
        override val doubleTapMinTimeMillis: Long
            get() = originalViewConfiguration.doubleTapMinTimeMillis
        override val doubleTapTimeoutMillis: Long
            get() = originalViewConfiguration.doubleTapTimeoutMillis
        override val longPressTimeoutMillis: Long
            get() = originalViewConfiguration.longPressTimeoutMillis
        override val touchSlop: Float
            get() = 0f // set this to any value you want

    }
Kotlin

Finally, wrap the composable that you want to be affected by this change inside a CompositionLocalProvider as follows:

CompositionLocalProvider(LocalViewConfiguration provides viewConfiguration) {
        // anything here that uses drag gesture or scoll will be affected
        Column(){
        ........
        }
Kotlin

Full code

@Composable
fun MyComosable(modifier: Modifier) {
    val originalViewConfiguration = LocalViewConfiguration.current
    val viewConfiguration = object : ViewConfiguration {
            override val doubleTapMinTimeMillis: Long
                get() = originalViewConfiguration.doubleTapMinTimeMillis
            override val doubleTapTimeoutMillis: Long
                get() = originalViewConfiguration.doubleTapTimeoutMillis
            override val longPressTimeoutMillis: Long
                get() = originalViewConfiguration.longPressTimeoutMillis
            override val touchSlop: Float
                get() = 0f // set this to any value you want

    }
    CompositionLocalProvider(LocalViewConfiguration provides viewConfiguration) {
        // anything here that uses drag gesture or scoll will be affected
        Column(modifier = modifier){
            ........
        }
}
Kotlin

Conclusion

As you can see, it is very easy to change any ViewConfiguration propriety value using this way. And with the same way, you can change longPressTimeoutMillis and the rest of the properties.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top