Search code examples
androiddialogonbackpressed

Prevent to close dialog show automatically in the onBackPressed method


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.


Solution

  • Comment or remove this line of code and try

    super.onBackPressed();