-1

I Wan to Show a dialog to the user if click on back button. I Used this create the onBackPressed method like this:

 @Override
  public void onBackPressed() {
    super.onBackPressed();

    if (isNew || !isReport) {

      if (!edtReportContent.getText().toString().isEmpty() && !edtReportContent.getText().toString().equals("")) {

        Toast.makeText(activity, "گزارش شما به عنوان پیش نویس ذخیره شد!", Toast.LENGTH_LONG).show();
        saveReport(1);

      } else {

        Toast.makeText(activity, "متن گزارش نمی تواند خالی باشد!", Toast.LENGTH_SHORT).show();
        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.dialog_remove_draft);

        Button btnDelete = (Button) dialog.findViewById(R.id.btn_delete);
        btnDelete.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {

            discardReport();

          }
        });

        dialog.setCancelable(false);
        dialog.show();
      }
  }

But when I click on the back button my dialog will show for a few seconds and disappear automatically! What is the problem?

Thank you for your answers.

Ehsan
  • 2,676
  • 6
  • 29
  • 56

2 Answers2

5

Comment or remove this line of code and try

super.onBackPressed();
Sunil P
  • 3,698
  • 3
  • 13
  • 20
0

Remove super.onBackPressed();. Your code will now look like this:

  @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
            return;
        }

        if(Close_Dialog==null) {
            Close_Dialog = new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setMessage("Are you sure you want to close ?")
                    .setPositiveButton("close", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MainActivity.super.onBackPressed();
                            overridePendingTransition(R.anim.right_in, R.anim.right_out);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .create();
        }

        if(Close_Dialog !=null)
        {
            if(!Close_Dialog.isShowing())
                Close_Dialog.show();
            else
                Close_Dialog.dismiss();
        }


    }
HB.
  • 4,116
  • 4
  • 29
  • 53
Mallikarjuna
  • 874
  • 6
  • 17