Jetpack Compose中的监听模式底部工作表布局状态更改 [英] Listen ModalBottomSheetLayout state change in Jetpack Compose

查看:15
本文介绍了Jetpack Compose中的监听模式底部工作表布局状态更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前使用的是ModalBottomSheetLayout来显示底部的工作表。

我不知道有没有办法收听底部页面关闭事件?

推荐答案

在编写以侦听更改时,您需要检查可变状态的当前值。

ModalBottomSheetLayout的情况下,您有ModalBottomSheetState,您可以检查currentValue的状态。如果需要,您可以根据此值修改视图状态。

如果您想对状态更改执行一些操作,则需要使用side effects。最基本的是LaunchedEffect,作为key,您可以传递一些您想要监视的值。每次更改此值时,将调用BLOCK:

LaunchedEffect(modalBottomSheetState.currentValue) {
    println(modalBottomSheetState.currentValue)
}

此外,当您启动屏幕时,将第一次调用我,并且您也将在那里拥有Hidden,因此根据您的需要,这可能不是理想的解决方案。


若要最接近隐藏时的监听,您可以使用DisposableEffect

if (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {
    DisposableEffect(Unit) {
        onDispose {
            println("hidden")
        }
    }
}

我在这里启动DisposableEffect,当您的工作表出现时,当它消失时-我将从视图层次结构中删除它,这将导致调用onDispose

基本上可以对状态执行的所有操作的完整示例:

val modalBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
val scope = rememberCoroutineScope()
LaunchedEffect(modalBottomSheetState.currentValue) {
    println(modalBottomSheetState.currentValue)
}
if (modalBottomSheetState.currentValue != ModalBottomSheetValue.Hidden) {
    DisposableEffect(Unit) {
        onDispose {
            println("hidden")
        }
    }
}
ModalBottomSheetLayout(
    sheetState = modalBottomSheetState,
    sheetContent = {
        Text(
            "sheetContent",
            modifier = Modifier.fillMaxHeight()
        )
    }
) {
    Column {
        Text(modalBottomSheetState.currentValue.toString())
        Button(onClick = {
            scope.launch {
                modalBottomSheetState.show()
            }
        }) {
            Text("Show bottom sheet")
        }
    }
}

这篇关于Jetpack Compose中的监听模式底部工作表布局状态更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆