Compose返回键监听方法
方法1
@Composable fun Back1(controller: NavHostController) { Column( Modifier .fillMaxSize() .background(Color.Red) .clickable { controller.popBackStack() }) { Text(text = "点击返回上一个页面") Text(text = "使用BackHandler实现返回键监听") } BackHandler(enabled = true) { Log.e("tag","返回键被点击") } } 复制代码
方法2
在@Composable方法中加入如下监听设置,方法1的实现方式就是使用如下方式实现的
@Composable fun Back2(controller: NavHostController) { Column( Modifier .fillMaxSize() .background(Color.Green) .clickable { controller.popBackStack() }) { Text(text = "点击返回上一个页面") Text(text = "使用OnBackPressedDispatcher监听返回键被点击") } val callback = remember { object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { log("回退键被点击") showToast("监听到返回键被点击监听") } } } val dispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher DisposableEffect(key1 = Unit, effect = { dispatcher?.addCallback(callback) onDispose { callback.remove() } }) }