How to show a dialog box after pressing the back button

Jyosna picture Jyosna · Aug 4, 2011 · Viewed 41k times · Source

By clicking the back button, I want to display a dialog box consisting of TextViews and a button called exit. After clicking the exit button it should come out from my app

I did like this,

@Override       
public void onBackPressed() {       
    System.out.println("hiiii");
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);

    Button exitButton = (Button) dialog.findViewById(R.id.exit);
    System.out.println("inside dialog_started");
    exitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            MainActivity.this.finish();
            dialog.dismiss();
        }
    });
    return;
}

in log cat hiiiii and "inside dialog_started" is printed, but dialog box is not coming. How can i get that dialog box on back button click?

Answer

Sandy picture Sandy · Aug 4, 2011
 public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();

        //moveTaskToBack(false);

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
    .setMessage("Do you want to exit application?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {

            finish();
            //close();


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

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
                       }
    })
      .show();

}