'How to disable drag Compose pager after upgrade to v0.19.0?

As title, Android Compose Pager layout removed dragEnabled after v0.19.0. Is there any other way to disable drag pager ?

Guide: https://google.github.io/accompanist/pager/



Solution 1:[1]

Since Accompanist 0.24.1-alpha, which requires Compose version 1.2.0-alpha02 or newer, userScrollEnabled argument was added:

HorizontalPager(
    userScrollEnabled = false
) {
}

It requires Compose 1.2.0-alpha01 because in this version same functionality was added to LazyColumn/LazyRow, which lays under Accompanist Pager.


If you're using Compose 1.1.0 or earlier, you can use the following solution:

Since version 0.19.0 the Accompaniment Pager has been re-written to be based on LazyRow and LazyColumn.

Lazy views do not support disabling scrolling for now, you can star this issue to bring more attention to this problem and follow updates.

Here's a workaround for now:

private val VerticalScrollConsumer = object : NestedScrollConnection {
    override fun onPreScroll(available: Offset, source: NestedScrollSource) = available.copy(x = 0f)
    override suspend fun onPreFling(available: Velocity) = available.copy(x = 0f)
}

private val HorizontalScrollConsumer = object : NestedScrollConnection {
    override fun onPreScroll(available: Offset, source: NestedScrollSource) = available.copy(y = 0f)
    override suspend fun onPreFling(available: Velocity) = available.copy(y = 0f)
}

fun Modifier.disabledVerticalPointerInputScroll(disabled: Boolean = true) =
    if (disabled) this.nestedScroll(VerticalScrollConsumer) else this

fun Modifier.disabledHorizontalPointerInputScroll(disabled: Boolean = true) =
    if (disabled) this.nestedScroll(HorizontalScrollConsumer) else this

Usage:

HorizontalPager(
    count = 10,
    modifier = Modifier.disabledHorizontalPointerInputScroll()
) {
    //...
}

Solution 2:[2]

A workaround you can use is declare a Box in front of your pager in order to intercept the drag gesture. Something like below:

var dragEnable by remember {
    mutableStateOf(true)
}

Box {
    HorizontalPager(...) { page ->
        // Content of your pager... 
    }
    if (!dragEnable) {
        // This box will intercept the drag gesture and do nothing.
        Box(
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(Unit) {
                    detectDragGestures(
                        onDrag = { change, offset ->
                            change.consumeAllChanges()
                        }
                    )
                },
        )
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2