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 就可以了

完事

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章