praew_z
praew_z

Reputation: 175

how to finish previous page when press the button

if every page have one button to go to home page how to end previous page because when I press home button and then press back button I want to exit the program

Upvotes: 0

Views: 352

Answers (1)

Chris Stewart
Chris Stewart

Reputation: 3299

In your home activity, which I'm assuming is presented when the home button is clicked from somewhere else in the app, you can catch the back button press and exit the app. The following will show a dialog asking if the user really wants to exit.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
        showDialog(DIALOG_REALLY_EXIT_ID);

    return false;
}

@Override
protected Dialog onCreateDialog(int id)
{
    final Dialog dialog;

    switch(id)
    {
        case DIALOG_REALLY_EXIT_ID:
            dialog = new AlertDialog.Builder(this)
                .setIcon(R.drawable.icon)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Home.this.finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).create();
            break;
        default:
            dialog = null;
    }

    return dialog;
}

Upvotes: 1

Related Questions