Android dialog报错:The specified child already has a parent. You must call removeView() on the chi...

Android dialog报错 The specified child already has a parent. You must call removeView on the child's parent first

问题描述

正在学kotlin的时候,写了一个简单的弹窗管理框架,但是最近发现弹窗消失后重新show,会出这个bug

解决方案

参考链接:https://stackoverflow.com/questions/41347744/android-dialog-error-the-specified-child-already-has-a-parent-you-must-call-rem
错误的代码:

open class BaseDialog(context: Context) {

    val mContext = context
    val dialog = AlertDialog.Builder(context)

    var alert: AlertDialog? = null

    fun show() {
        alert = dialog.show()
    }

    fun dismiss() {
        alert?.dismiss()
    }
}

修改后的代码:

open class BaseDialog(context: Context) {

    val mContext = context
    val dialog = AlertDialog.Builder(context)

    var alert: AlertDialog? = null

    fun show() {
        alert?.show()
    }

    fun dismiss() {
        alert?.dismiss()
    }
}

提前在 dialog.create() 的时候就赋值给 alert 就可以了

完事

发布了103 篇原创文章 · 获赞 31 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/sinat_38184748/article/details/103204747