Intercepting the back button

后端 未结 4 1380
自闭症患者
自闭症患者 2020-12-10 01:39

I\'m writing an application which will have two Activities, when the user presses the back button on the second activity a dialog should pop up asking the user to confirm th

4条回答
  •  醉梦人生
    2020-12-10 02:07

    By the docs, do not use onBackPressed if you can. Now is recommended using onBackPressedDispatcher.addCallback(this) {}. There's a Fragment example:

    class MyFragment : Fragment() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // This callback will only be called when MyFragment is at least Started.
            val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
                // Handle the back button event
            }
    
            // The callback can be enabled or disabled here or in the lambda
        }
        ...
    }
    

提交回复
热议问题