LinggaMG
LinggaMG

Reputation: 83

ModalBottomSheetLayout and back pressed

Currently I am using Jetpack compose and use ModalBottomSheetLayout to display the bottom sheet.

How to hide sheetState when back pressed?

Upvotes: 8

Views: 3764

Answers (2)

SpiritCrusher
SpiritCrusher

Reputation: 21053

You can use BackHandler .. Something like this .

 val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
ModalBottomSheetLayout() {
    Scaffold() { innerPadding ->
        // Content goes here
        BackHandler(enabled = modalBottomSheetState.isVisible) {
            coroutineScope.launch {
                modalBottomSheetState.hide()
            }
        }
    }
}

Upvotes: 20

Soufian
Soufian

Reputation: 90

You can use state for that and hide the sheet when the user presses the back button.

class SheetActivity : AppCompatActivity() {
    private val sheetState = mutableStateOf(ModalBottomSheetValue.Expanded)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme(colors = lightColorPalette()) {
                ModalBottomSheetLayout(
                    sheetState = sheetState.value,
                    sheetContent = {
                        BottomSheetContent()
                    }
                )
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        sheetState.value = ModalBottomSheetValue.Hidden
    }
}

@Composable
fun BottomSheetContent() {
    Column {
        Text("Sheet")
    }
}

Upvotes: 0

Related Questions