Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Proper Way to use onBackPressed() with Toast

Tags:

android

I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!

Code:

public void onBackPressed(){     backpress = (backpress + 1);     Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();      if (backpress>1) {         this.finish();     } } 
like image 436
Nick Avatar asked Jun 20 '11 15:06

Nick


People also ask

How do I use onBackPressed?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.


1 Answers

I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.

@Override public void onBackPressed() {     new AlertDialog.Builder(this)         .setTitle("Really Exit?")         .setMessage("Are you sure you want to exit?")         .setNegativeButton(android.R.string.no, null)         .setPositiveButton(android.R.string.yes, new OnClickListener() {              public void onClick(DialogInterface arg0, int arg1) {                 WelcomeActivity.super.onBackPressed();             }         }).create().show(); } 

In the above example, you'll need to replace WelcomeActivity with the name of your activity.

like image 81
Steve Prentice Avatar answered Oct 01 '22 13:10

Steve Prentice