所以,这可能是一个有点矫枉过正的解决方案,但我们的团队已经厌倦了不得不担心每个 RecyclerView 适配器泄漏。
这是一个抽象的 RecyclerView.Adapter 子类,它一劳永逸地处理泄漏问题。
abstract class AbstractRecyclerViewAdapter<VH : RecyclerView.ViewHolder>(fragment: Fragment) :
RecyclerView.Adapter<VH>() {
private val fragmentRef = WeakReference(fragment)
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
setupLifecycleObserver(recyclerView)
}
private fun setupLifecycleObserver(recyclerView: RecyclerView) {
val fragment = fragmentRef.get() ?: return
val weakThis = WeakReference(this)
val weakRecyclerView = WeakReference(recyclerView)
// Observe the fragment's lifecycle events in order
// to set the Recyclerview's Adapter when the Fragment is resumed
// and unset it when the Fragment is destroyed.
fragment.viewLifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
val actualRecyclerView = weakRecyclerView.get() ?: return
when (event.targetState) {
Lifecycle.State.DESTROYED -> actualRecyclerView.adapter = null
Lifecycle.State.RESUMED -> {
val self = weakThis.get() ?: return
if (actualRecyclerView.adapter != self) {
actualRecyclerView.adapter = self
}
}
else -> {
}
}
}
})
}
}
基本上,适配器会观察包含它的 Fragment 的生命周期事件,并负责将自身设置和取消设置为 RecyclerView 的适配器。
您需要做的就是AbstractRecyclerViewAdapter
在您自己的适配器中进行子类化,并在构建它们时提供容器片段。
用法:
你的适配器
class MyAdapter(fragment: Fragment): AbstractRecyclerViewAdapter<MyViewHolder>(fragment) {
// Your usual adapter code...
}
你的片段
class MyFragment : Fragment {
// Instantiate with the fragment.
private val myAdapter = MyAdapter(this)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Set the RecyclerView adapter as you would normally.
myRecyclerView.adapter = myAdapter
}
}