本文介绍了当 alertdialog 的 setcancelable 为 false 时,无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 AlertDialog,它的 setCancelable()
是假的.在 Onbackpressed
函数中,我希望关闭 AlertDialog.但是当 setCancelable()
为 false 时,后退键根本不起作用.我应该怎么做才能摆脱这个问题?我不想将 setCancelable()
更改为 true,因为我会遇到另一个问题.
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()
}
}
推荐答案
只需添加一个 onKeyListener 并取消返回键事件的对话框.
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
}
}
这篇关于当 alertdialog 的 setcancelable 为 false 时,无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!