在测试我的应用程序时,我意识到,如果用户快速多次按下FloatingActionButton,onClick回调可能会被多次触发.在我的例子中,这导致后栈被多次弹出,因为onPopBackStack回调冒泡到NavHost,在那里它可以访问navController并调用popBackStack方法.

fun AddEditTodoScreen(onPopBackStack: () -> Unit, viewModel: AddEditTodoViewModel = viewModel()) {

    var isNavigating by remember{
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = true){
        viewModel.uiEvent.collect{event : UiEvent ->
            when(event){
                is UiEvent.PopBackStack -> onPopBackStack
                else -> Unit
            }
        }
    }

    Scaffold(floatingActionButton = {
        FloatingActionButton(onClick = {
            if(!isNavigating){
                isNavigating = !isNavigating
                onPopBackStack()
            }
        }) {
            Icon(imageVector = Icons.Default.Check, contentDescription = "Check")
        }

目前,我只是在第一次单击FloatingActionButton时将isNavigating设置为True,如果再次单击,它将判断isNavigating标志是否设置为True,如果设置为True,则不执行任何操作.如果有更好的办法来解决这个问题,还有什么办法?

推荐答案

导航已经告诉你是否要导航到一个新的目的地:当你拨打navigate时,NavBackStackEntry中的Lifecycle会同步改变,使你从RESUMED状态向下移动.

因此,如果您想要避免在已经开始导航到另一个屏幕之后处理点击,您需要判断LocalLifecycleOwner‘S状态:

// This corresponds with the NavBackStackEntry
// associated with this screen
val lifecycleOwner = LocalLifecycleOwner.current

FloatingActionButton(onClick = {
    // Get the current state of the Lifecycle
    val currentState = lifecycleOwner.lifecycle.currentState

    // And ignore click events when you've started navigating
    // to another screen
    if (currentState.isAtLeast(Lifecycle.State.RESUMED)) {
        onPopBackStack()
    }
}

Android相关问答推荐

打开平板电脑的下载文件夹中的文件,例如使用其mimeType将Intent发送到我们的应用程序

滑动以更改合成中的活动

AdMob:MobileAds. initialize()—java. lang. xml对于某些设备不能强制转换为java. lang. String""

无法安装后重新编译android代码'

关于BLE扫描工作原理的说明

懒惰的垂直网格中盒子的重量-Jetpack组合

安卓Gradle看不到dagger 柄

原始mp3文件不显示与proguard

保护所有程序包文件和类

如何更新Kotlin中的显示?

如何用帆布在喷气背包中画一个圆环?

如何在DownloadManager Android中显示ProgressBar和Complete Listener

更改活动(上下文)对接收到的uri的访问权限的影响?

Andorid Studio编译器如何自动为变量editText生成mutableStateOf("")的方法名?

Android Jetpack Compose全宽度抽屉优化

在 Android 房间迁移中获取上下文

在 Material 3 TopAppBar 代码的哪个位置定义了填充?

将房间中的实体更新为 isCompleted 并使用 Flow 问题获取所有数据

房间实时数据:启动时崩溃

如何使 BasicTextField 上的光标以 jetpack compose 为中心?