点击后退按钮两次以终止 Fragment 中的应用程序

Tap back button twice to terminate application in Fragment

我正在实现一个功能,即通过单击后退按钮两次关闭应用程序。它在首次单击时显示 toast 消息。但是,问题是它显示无限循环错误然后被终止。翻了两天也不太明白是什么原因。任何帮助将不胜感激。

My fragment code

    class RegisteredMainFragment : Fragment() {

    private lateinit var binding : FragmentRegisteredMainBinding
    private val viewModel : RegisteredMainViewModel by inject()

    private lateinit var mContext: MainActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context as MainActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_registered_main, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner
      
        onBackPressedCallback()
    }

    private fun onBackPressedCallback() {
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
            object : OnBackPressedCallback(true ) {
                override fun handleOnBackPressed() {
                    if (doubleBackToExitPressedOnce) {
                        requireFragmentManager().popBackStack()
                        return
                    }
                    doubleBackToExitPressedOnce = true
                    Toast.makeText(requireContext(), "click back button again", Toast.LENGTH_SHORT).show()
                    Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        viewModel.onAuthExist()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        PushObserverService.unregisterObserver(this)
    }
}

我把它写在override fun onAttach中解决了这个问题 请检查下面的代码

    override fun onAttach(context: Context) {
    super.onAttach(context)
    mContext = context as MainActivity

    callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if (doubleBackToExitPressedOnce) {
                activity?.finish()
            }
            doubleBackToExitPressedOnce = true
            Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            showSnackBar(
                context = mContext,
                layout = binding.layoutMain,
                type = Constants.SnackBarTypes.Warn,
                message = mContext.getString(R.string.tap_twice_to_terminate)
            )
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}