Home > Enterprise >  ModalBottomSheetLayout and back pressed
ModalBottomSheetLayout and back pressed

Time:07-09

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

How to hide sheetState when back pressed?

CodePudding user response:

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()
            }
        }
    }
}

CodePudding user response:

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")
    }
}
  • Related