单击返回按钮时,该应用在seceond之后崩溃
我自定义了后退按钮。当我点击它时,应用程序在一秒钟后崩溃。 这是代码: 错误日志
private var mBackPressed: Long = 0
private val timeInterval = 2000
private fun configBackPress() {
requireActivity().onBackPressedDispatcher.addCallback(this, true) {
when {
mBackPressed + timeInterval > System.currentTimeMillis() -> {
requireActivity().onBackPressedDispatcher.onBackPressed()
}
else -> {
Snackbar.make(
requireActivity().findViewById(android.R.id.content),
getString(R.string.press_once_again_back_button_to_exit),
Snackbar.LENGTH_SHORT
)
.setAnchorView(viewBinding.vSnackBarHelper)
.show()
mBackPressed = System.currentTimeMillis()
}
}
}
}
当用户单击后退按钮两次时,后退应该可以工作。
I have customized back button. when I click on it, the application crashes after a second.
here is the code:
error log
private var mBackPressed: Long = 0
private val timeInterval = 2000
private fun configBackPress() {
requireActivity().onBackPressedDispatcher.addCallback(this, true) {
when {
mBackPressed + timeInterval > System.currentTimeMillis() -> {
requireActivity().onBackPressedDispatcher.onBackPressed()
}
else -> {
Snackbar.make(
requireActivity().findViewById(android.R.id.content),
getString(R.string.press_once_again_back_button_to_exit),
Snackbar.LENGTH_SHORT
)
.setAnchorView(viewBinding.vSnackBarHelper)
.show()
mBackPressed = System.currentTimeMillis()
}
}
}
}
when the user click two times on back button, the back should work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在调用 requireActivity().onBackPressedDispatcher.onBackPressed() 之前。您应该将

isEnabled
设置为 false,因为如果我们查看 onBackPressed 源代码,我们会看到:它查找活动回调,如果找到任何回调,则调用它们并返回。这就是循环的原因。
你的代码应该是:
before calling

requireActivity().onBackPressedDispatcher.onBackPressed()
. you should setisEnabled
to false because if we go through the onBackPressed source code we see:it looks for active callbacks and if found any calls them and returns. that's what makes the loop.
your code should be:
)
d
fragment
在(onbackpressed
in(requiend> required requecre
decrip /code>,最初将尝试将此事件传播到拥有儿童 -fragment
s。因此,再次,将触发onbackpresseddispatcher
,它将再次调用活动
s方法,这是您的日志屏幕截图中描述的无尽循环(btw。从不post code/log/log/log/log/log/log/log/文本为图像!)编辑:
isEnabled = false
是一种更好的方法,只想留下一些案例描述replace
with just
currently your
onBackPressedDispatcher
set inFragment
is callingonBackPressed
in (require
d)Activity
, which will at first try to propagate this event to own childrens -Fragment
s. so, again,onBackPressedDispatcher
will be triggered, again it will callActivity
s method and this is an endless loop depicted in your log screenshot (btw. never post code/log/text as image!)edit:
isEnabled = false
is a better approach, just wanted to leave you some case description