Back Button Action



Generally on pressing the back button, an activity is ended. But there may be a need to show a message or dialog box about the confirmation of the end of the activity. Or there may be other events that someone may want to be performed on pressing the back button.

  • Use the method onBackPressed() from the class Activity and write the events in this method.
  • public void onBackPressed() {

    // TODO Auto-generated method stub

    }





  • To show the dialog box, write the code of AlertDialogBox. For example-
  • public void onBackPressed() {

    // TODO Auto-generated method stub

    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);

    dialog.setTitle("My App");

    dialog.setMessage("Do you really want to quit?");

    dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface arg0, int arg1) {

    }

    });

    dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){

    @Override

    public void onClick(DialogInterface dialog, int which) {

    MainActivity.this.finish();

    }

    })

    .show();

    }
  • Note that the statement in onClick() method MainActivity.this.finish(); of PositiveButton is responsible to end the activity on clicking this button.
  • android