这是一个扩展 xml 文件的对话框片段。然后,该对话框片段将作为弹出窗口在另一个片段中使用。
我正在尝试覆盖后退按钮,其中后退按钮不应关闭/关闭对话框片段。它应该只通过视图模型传递实时数据并显示一条消息“按下后退按钮!您无法在此处退出”。
目前,当我按下后退按钮时,对话框片段仍然会消失。我该如何解决这个问题?
class MsicUpdateLater : DialogFragment() {
private val sharedViewModel: BrnViewModel by activityViewModels()
private lateinit var backPressedCallback: OnBackPressedCallback
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.FullWidthSheetDialog)
backPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// is this the right way?
Toast.makeText(requireContext(), "Back Button Pressed! You can't exit at here", Toast.LENGTH_SHORT).show()
sharedViewModel.msicDialogFragment()
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, backPressedCallback)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.brn_tin_update_later_pop_up, container, false)
}
override fun onDestroyView() {
super.onDestroyView()
backPressedCallback.remove()
}
}
Window
。这意味着所有按键事件(包括系统后退按钮)都会首先路由到对话框,这意味着活动级别的任何内容(包括活动的 OnBackPressedDispatcher
)都无法在对话框本身处理这些按键事件之前拦截它们。
ComponentDialog
(及其子类,如 AppCompat 1.5.0 及更高版本的 AppCompatDialog
)将其公开为自己的 OnBackPressedDispatcher
.
这意味着您应该首先通过将该依赖项添加到您的 build.gradle 文件中来确保您使用的是 Fragment 1.6.1 或更高版本:
// Consider upgrading to Fragment 1.7.1 or the latest stable, 1.8.1
implementation "androidx.fragment:fragment:1.6.2"
然后更改代码以访问对话框的
onBackPressedDispatcher
。请注意,ComponentDialog
还实现了LifecycleOwner
,因此如果您在添加回调时将对话框作为LifecycleOwner
传递,则根本不需要手动删除回调:
class MsicUpdateLater : DialogFragment() {
private val sharedViewModel: BrnViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.FullWidthSheetDialog)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Get the Dialog itself
val dialog = requireComponentDialog()
// Now add the callback using the addCallback Kotlin extension
// Make sure to add import androidx.activity.addCallback
dialog.onBackPressedDispatcher.addCallback(
owner = dialog
) {
// The Kotlin extension uses a trailing lambda
// for the handleOnBackPressed() method
Toast.makeText(requireContext(), "Back Button Pressed! You can't exit at here",
Toast.LENGTH_SHORT).show()
sharedViewModel.msicDialogFragment()
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.brn_tin_update_later_pop_up, container, false)
}
}