3

I’m trying to add swipe to dismiss to a LazyList.

The default implementation of SwipeToDismiss will lead to accidental horizontal scrolling while trying to scroll vertically leading to accidental swipe to dismiss events.

In vanilla android view world i'd set a touch listener and check against x > y touch event distance before starting swipe to dismiss. However in Jetpack Compose I don't know how.

I tried pointerInput modifier, however it disabled vertical scrolling completely.

I’m aware of dismissThresholds but that does only handle invoking the dismissState change.

@Composable
fun MyList(modifier: Modifier = Modifier, list: MutableState<List<String>>) {

    val scrollState: LazyListState = rememberLazyListState()

    LazyColumn(
        modifier = modifier
            .fillMaxWidth()
            .background(MaterialTheme.colors.surface),
        state = scrollState,
    ) {
        items(
            items = list.value,
            key = { it },
            contentType = { 0 }
        ) { item ->
            MySwipeToDismiss(modifier = modifier, onSwipeLeft = {}, onSwipeRight = {}) {
                Text(text = item)
            }
        }
    }
}
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MySwipeToDismiss(modifier: Modifier = Modifier, onSwipeLeft: () -> Unit, onSwipeRight: () -> Unit, content: @Composable () -> Unit) {

    val dismissState = rememberDismissState {
        when (it) {
            DismissValue.Default -> return@rememberDismissState false
            DismissValue.DismissedToEnd -> onSwipeRight()
            DismissValue.DismissedToStart -> onSwipeLeft()
        }
        true
    }

    SwipeToDismiss(
        modifier = modifier,
        state = dismissState,
        dismissThresholds = { FractionalThreshold(0.7f) },
        background = {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Cyan)
            )
        }
    ) {
        content()
    }
}

Any suggestion is highly appreciated.

Kibotu
  • 173
  • 8

0 Answers0