FragmentExtensions.kt
TLDR
This file provides an extension function for the Activity
class to register a callback that will be triggered when a fragment's view is destroyed.
Methods
onAndroidXFragmentViewDestroyed
This method is an extension function for the Activity
class. It checks if the AndroidX Fragment Activity is available and if the current activity is an instance of the FragmentActivity
class. If both conditions are met, it registers a FragmentManager.FragmentLifecycleCallbacks
object with the support fragment manager. The callback's onFragmentViewDestroyed
method is triggered when a fragment's view is destroyed, and it executes the provided block
of code.
package leakcanary.internal
import android.app.Activity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
private val hasAndroidXFragmentActivity: Boolean by lazy {
try {
Class.forName("androidx.fragment.app.FragmentActivity")
true
} catch (ignored: Throwable) {
false
}
}
internal fun Activity.onAndroidXFragmentViewDestroyed(block: () -> Unit) {
if (!hasAndroidXFragmentActivity) {
return
}
if (this is FragmentActivity) {
supportFragmentManager.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewDestroyed(
fm: FragmentManager,
fragment: Fragment
) {
block()
}
}, true
)
}
}