Pin a view to Bottom Sheet in Jetpack Compose

Viewed 135

I'm trying to implement a persistent Bottom Sheet in Jetpack Compose which has a button that should be pinned to the bottom of this sheet at all time, it shouldn't get dragged with the other contents when expanding. I couldn't find an easy way to do it except manipulating other views heights relative to the bottom sheet state which is hard to maintain. Any idea how can I achieve that?

Here's an illustration for what I'm trying to achieve

1 Answers

Tricky part is getting initial offset of button or sheet content. I did it with a class

class OffsetWrapper(var offset: Float = 0f)

Then all you need to do is calling Modifier.offset{} on Button with initial position of button minus current offset of bottomSheetState.offset.value

@ExperimentalMaterialApi
@Composable
private fun SheetContent(bottomSheetState: BottomSheetState) {

    val offsetWrapper = remember { OffsetWrapper() }

    if (offsetWrapper.offset == 0f) {
        val offset = bottomSheetState.offset.value
        offsetWrapper.offset = offset
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        Button(
            modifier = Modifier
                .padding(8.dp)
                .fillMaxWidth()
                .offset {
                    IntOffset(0,
                        (-bottomSheetState.offset.value+ offsetWrapper.offset).toInt()
                    )
                }
            ,
            onClick = { /*TODO*/ }) {
            Text("Button")
        }
    }
}
Related