Cause: github.com/hehonghui/a…

The solution mentioned in this article has a minor problem. In the second show, after the dialog disappears, because the onWindowDetached() method is called back, the click callback event is cleared, resulting in no feedback for the dialog button click event in the second show. Lifecycle events are provided by Android to nullify the click callback agent when the onDestory lifecycle function is executed.

The specific code is as follows:

/** * avoid Dialog memory leak * @property delegateOrNull OnClickListener? * @constructor */ class DetachableClickListener private constructor( private var delegateOrNull: DialogInterface.OnClickListener? ) : DialogInterface.OnClickListener, LifecycleObserver { override fun onClick(dialog: DialogInterface,which: Int) { delegateOrNull? .onClick(dialog,which)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun clearOnDetach() { delegateOrNull = null } companion object { @JvmStatic fun wrap(delegate: DialogInterface.OnClickListener?) : DetachableClickListener {return DetachableClickListener(delegate)
            }
        }
    }

Copy the code

Use:

val detachableClickListener = DetachableClickListener .wrap(DialogInterface.OnClickListener { dialog, _ -> callBackListener? .onClickPositive(dialog) })setPositiveButton(positiveText, detachableClickListener)
                if (context is FragmentActivity) {
                    context.lifecycle.addObserver(detachableClickListener)
                }
Copy the code