Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Overriding onBackPressed()

Is it possible to override onBackPressed() for only one activity ?

On back button click I want to call a dialog on a specific Activity, but in all other activities i want it to work as it worked before (going to previous activities).

EDITED

Thank you everyone for your answers, I already had everything like you told me, but my problem was that when i was clicking back button on another Activity, I was going to my previous Activity (The one where i had back button Overridden) and i thought that it wasn't working, i thought it was overriding onBackPressed() in whole Application, now i got it.

like image 227
Jilberta Avatar asked Aug 20 '13 14:08

Jilberta


People also ask

Does onBackPressed destroy activity?

But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it. Please see here for a great write-up on the topic.

What happens when back button is pressed in Android?

However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states. But we do not want to lose this data. To retain the data, we need to override the back pressed method.


1 Answers

Yes. Only override it in that one Activity with

@Override public void onBackPressed() {      // code here to show dialog      super.onBackPressed();  // optional depending on your needs } 

don't put this code in any other Activity

like image 96
codeMagic Avatar answered Sep 19 '22 15:09

codeMagic