栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

让 androidx.appcompat.app.AlertDialog 保持住不关闭

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

让 androidx.appcompat.app.AlertDialog 保持住不关闭

有时候AlertDialog带有逻辑判断,不符合条件的时候想继续显示对话框,但是点击了按钮默认是会关闭对话框的,又不想自定义Dialog,经研究测试,下面的方式可以达到预期效果:

fun AlertDialog.keep(text: String = "确定", listener: DialogInterface.OnClickListener? = null): AlertDialog {
    getButton(DialogInterface.BUTTON_POSITIVE).let { positiveButton ->
        positiveButton.visibility = View.VISIBLE
        positiveButton.text = text
        positiveButton.setOnClickListener {
            listener?.onClick(this, DialogInterface.BUTTON_POSITIVE)
        }
    }
    return this
}

调用的时候记得先 show() 再 keep()

    private fun showPasswordDialog() {
        val editText = EditText(this)
        AlertDialog.Builder(this)
            .setCancelable(false)
            .setTitle("请输入密码")
            .setView(editText)
//            .setPositiveButton("确定", null)
            .setNegativeButton("取消") { _, _ -> finish() }
            .show().keep("确定") { dialog, _ ->
                val pwd = editText.text.toString().trim().toByteArray()
                if ((application as App).getPassword("XXX").contentEquals(pwd)) {
                    //密码正确,关闭对话框
                    dialog.dismiss()
                } else {
                    showToastOnUI("密码错误")
                }
            }
    }

如果想改变“取消”按钮的行为,就给 mButtonNegative 设置监听器。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926584.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号