Not working onbackpressed when setcancelable of alertdialog is false

风格不统一 提交于 2020-05-20 07:35:07

问题


I have an AlertDialog and its setCancelable() is false. In Onbackpressed function I want the AlertDialog to be closed. But when setCancelable() is false, the back key doesn't work at all. What should I do to get rid of this problem? I don't want to change setCancelable() to true because I will have another problem.

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var dialogBuilder: AlertDialog.Builder
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage("Check your internet connection")
            .setPositiveButton("OK") { _, _ ->
                Toast.makeText(this, "OK", Toast.LENGTH_LONG).show()
            }.setCancelable(false)
            .create().show()
    }
}

回答1:


just add a onKeyListener and cancel dialog on back key event.

    lateinit var dialog: AlertDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dialog = AlertDialog.Builder(this).setMessage("Check your internet connection")
                .setPositiveButton("OK") { _, _ ->
                    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show()
                }.setCancelable(false)
                .create()
        dialog.show()

        dialog.setOnKeyListener { _, keyCode, _ ->
            if(keyCode == KeyEvent.KEYCODE_BACK) {
                if(dialog.isShowing) {
                    dialog.dismiss()
                }
            }
            true
        }
    }



回答2:


The easiest work-around for this problem is to set an OnKeyListener and automatically detect when the user hits the back button.

Java:

public Dialog onCreateDialog(Bundle savedInstanceState) {

  Dialog dialog = super.onCreateDialog(savedInstanceState);

  dialog.setOnKeyListener(new Dialog.OnKeyListener() {
    @Override
    public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {
          dialog.cancel;
          return true;
        }
        return false;
    }
  });

  return dialog;
}

Kotlin:

    dialog = AlertDialog.Builder(this)
            .setCancelable(false)
            .create()
    dialog.show()

    dialog.setOnKeyListener (object : Dialog.OnKeyListener { 
      override fun onKey(dialogInterface: DialogInterface, keyCode: Int, keyEvent: KeyEvent) {
        if(keyCode == KeyEvent.KEYCODE_BACK and keyEvent.action == KeyEvent.ACTION_UP) {
            dialog.dismiss()
            true
        }
        false
      }})

Note that I added an extra condition in the if-statement, all this does is to make sure this does not fire twice.

I hope this helps you.




回答3:


As i see you create dialogBuilder is public why not you call this in a public alertDialog and than show it using alertDilog.show() and close on back pressClick in activity and dismiss the dialog alertDilog.dismiss() override the onBackPress and dismiss it here

val alertDialog:AlertDialog?=null


         alertDialog = new AlertDialog.Builder(this)
        //set icon 
        .setIcon(android.R.drawable.ic_dialog_alert)
        //set title
        .setTitle("Are you sure to Exit")
        //set message
        .setMessage("Exiting will call finish() method")
        //set positive button
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        //set what would happen when positive button is clicked    
            finish();
        }
        })
        //set negative button
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        //set what should happen when negative button is clicked
            Toast.makeText(getApplicationContext(),"Nothing 
          Happened",Toast.LENGTH_LONG).show();
         }
        })
        .show();

       onBackPress(){alertDialog.dismiss()}



回答4:


dialogBuilder.setOnKeyListener(object : OnKeyListener() {
            fun onKey(dialog: DialogInterface, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
//if you want to cancel the dialog only
                    dialog.cancel()
                    //if you want to finish then 
                   // finish()
                }
                return true
            }
        })



回答5:


if you don't want to close the dialog when touched outside area of the dialog, you can set the property

    permissionDialog.setCanceledOnTouchOutside(false)

and if you want to dismiss the dialog on backpress you need to call the method on keyListener

 permissionDialog?.setOnKeyListener { dialog, keyCode, _ ->
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dialog?.dismiss()
            true
        }
        false
    }


来源:https://stackoverflow.com/questions/60462748/not-working-onbackpressed-when-setcancelable-of-alertdialog-is-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!