Intercepting the back button

后端 未结 4 1379
自闭症患者
自闭症患者 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 01:49

    As schwiz pointed out, you'll want to override the onBackPressed() method in your activity class (http://developer.android.com/reference/android/app/Activity.html#onBackPressed()).

    I just wanted to add that if you did want to at some stage continue with or access the standard the back operation (after say, displaying a dialog), then you simply call super.onBackPressed() or ActivityName.super.onBackPressed() from anywhere in the Activity.

    0 讨论(0)
  • 2020-12-10 01:53

    Simply override the onKeyDown(int, KeyEvent) method in your activity and look for the back button. Return true so that the event is consumed.

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //Do something here
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-10 02:05

    In an activity you can just override

    onBackPressed()

    edit: that is api lvl 5+ :/ for 4 and below you gotta override onKeyDown()

    0 讨论(0)
  • 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
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题