Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting the back button

Tags:

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 the action. So how do I intercept this? I seriously doubt about this coz the backstack is a part of the OS itself. Has anyone found a workaround?

like image 264
Ragunath Jawahar Avatar asked Sep 01 '10 03:09

Ragunath Jawahar


People also ask

How do you intercept Back button on Flutter?

In simple cases, when you need to intercept the Android back-button, you usually add WillPopScope to your widget tree. However, when developing stateful widgets that interact with the back button, it's more convenient to use the BackButtonInterceptor .

What is WillPopScope Flutter?

The WillPopScope widget comes with the Flutter framework. It gives us control over the back button action, allowing the current page to go back to the previous one if it meets certain requirements. This is achieved using a callback, which the widget takes in as one of its parameters.

How do I turn off back Flutter?

To disable back button in Flutter, you can use the WillPopScope widget. The WillPopScope widget helps you get a callback whenever the back button is pressed. Inside the callback, if you return true the screen will be popped and if you return false, you have simply disabled the back button.


2 Answers

In an activity you can just override

onBackPressed()

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

like image 152
Nathan Schwermann Avatar answered Sep 19 '22 10:09

Nathan Schwermann


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); } 
like image 21
skorulis Avatar answered Sep 20 '22 10:09

skorulis