gpt4 book ai didi

android - OnBackPressedCallback 未在 Bottom Sheet 对话框 fragment 中调用

转载 作者:行者123 更新时间:2023-12-03 10:11:17 28 4
gpt4 key购买 nike

我有一个 Bottom Sheet Dialog Fragment其中包含四个 FragmentViewPager .
我想在 onBackPressed 时调用一个方法点击Bottom Sheet Dialog Fragment .已实现 OnBackPressedCallback在我的OnCreateView但它没有被触发。任何人都知道为什么不调用它?

val callback = object : OnBackPressedCallback(true */ true means that the callback is enabled /*) {
override fun handleOnBackPressed() {
// Show your dialog and handle navigation
LogUtils.d("Bottom Sheet -> Fragment BackPressed Invoked")
}
}

// note that you could enable/disable the callback here as well by setting callback.isEnabled = true/false
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback)

最佳答案

我在寻找 DialogFragment 中存在的相同问题的解决方案时发现了这个线程。答案在上面的评论中,但为了完整起见,这里是汇总的信息:
解决方案
在您的 DialogFragment 中覆盖 onCreateDialog 并设置 OnKeyListener:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
setOnKeyListener { _: DialogInterface, keyCode: Int, keyEvent: KeyEvent ->
if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == KeyEvent.ACTION_UP) {

// <-- Your onBackPressed logic here -->

return@setOnKeyListener true
}
return@setOnKeyListener false
}
}
}
解释
来自针对 requireActivity().onBackPressedDispatcher.addCallback 提出的问题不适用于 DialogFragments ( https://issuetracker.google.com/issues/149173280 ):

Dialogs are separate windows that always sit above your activity's window. This means that the dialog will continue to intercept the system back button no matter what state the underlying FragmentManager is in, or what code you run in your Activity's onBackPressed() - which is where the OnBackPressedDispatcher plugs into.


本质上是 onBackPressedDispatcher当使用任何使用对话框的组件时,它是错误的工作工具,因为它们在应用程序中的行为方式以及在 Activity 之外(在顶部)存在的方式。

关于android - OnBackPressedCallback 未在 Bottom Sheet 对话框 fragment 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59982321/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com