How to show a dialog to confirm that the user wishes to exit an Android Activity?
I've been trying to show a "Do you want to exit?" type of dialog when the user attempts to exit an Activity.
However I can't find the appropriate API hooks. Activity.onUserLeaveHint()
initially looked promising, but I can't find a way to stop the Activity开发者_开发百科 from finishing.
In Android 2.0+ this would look like:
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
In earlier versions it would look like:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
YourClass.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ExampleActivity.super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
Have modified @user919216 code .. and made it compatible with WebView
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
I'd prefer to exit with double tap on the back button than with an exit Dialog.
In this solution, it show a toast when go back for the first time, warning that another back press will close the App. In this example less than 4 seconds.
private Toast toast;
private long lastBackPressTime = 0;
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", 4000);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
Token from: http://www.androiduipatterns.com/2011/03/back-button-behavior.html
If you are not sure if the call to "back" will exit the app, or will take the user to another activity, you can wrap the above answers in a check, isTaskRoot(). This can happen if your main activity can be added to the back stack multiple times, or if you are manipulating your back stack history.
if(isTaskRoot()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourActivity.super.onBackPressed;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
super.onBackPressed();
}
in China, most App will confirm the exit by "click twice":
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Using Lambda:
new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
.setTitle(getString(R.string.info))
.setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
moveTaskToBack(true);
finish();
})
.setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
})
.show();
You also need to set level language to support java 8 in your gradle.build:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
First remove super.onBackPressed();
from onbackPressed()
method than and below code:
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Just put this code in your first activity
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
}
else {
// if your using fragment then you can do this way
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
} else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
}
I like a @GLee approach and using it with fragment like below.
@Override
public void onBackPressed() {
if(isTaskRoot()) {
new ExitDialogFragment().show(getSupportFragmentManager(), null);
} else {
super.onBackPressed();
}
}
Dialog using Fragment:
public class ExitDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.exit_question)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getDialog().cancel();
}
})
.create();
}
}
Another alternative would be to show a Toast
/Snackbar
on the first back press asking to press back again to Exit, which is a lot less intrusive than showing an AlertDialog
to confirm if user wants to exit the app.
You can use the DoubleBackPress Android Library
to achieve this with a few lines of code. Example GIF showing similar behaviour.
To begin with, add the dependency to your application :
dependencies {
implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}
Next, in your Activity, implement the required behaviour.
// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);
// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
@Override
public void actionCall() {
// TODO : Exit the application
finish();
System.exit(0);
}
};
// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
.withDoublePressDuration(3000) // msec - wait for second back press
.withFirstBackPressAction(firstBackPressAction)
.withDoubleBackPressAction(doubleBackPressAction);
Finally, set this as the behaviour on back press.
@Override
public void onBackPressed() {
doubleBackPress.onBackPressed();
}
精彩评论