Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a dialog box after pressing the back button

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?

like image 276
Jyosna Avatar asked Aug 04 '11 07:08

Jyosna


People also ask

What is a dialog button?

Dialog controls are modal UI overlays that provide contextual app information. They block interactions with the app window until being explicitly dismissed. They often request some kind of action from the user.

How do you inflate dialog?

To inflate the layout in your DialogFragment , get a LayoutInflater with getLayoutInflater() and call inflate() , where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. You can then call setView() to place the layout in the dialog.

How do you press back button?

just use finish(); – V.J. @user1216003 you are on right way. you will do same as back button with setting the flag in intent.


1 Answers

 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();

}
like image 93
Sandy Avatar answered Sep 18 '22 05:09

Sandy