如何在RecyclerView.Adapter中获取LifecycleOwner的引用?

3

目前我使用 mContext as LifecycleOwner 来获取 LifecycleOwner,它能够工作,但我认为这不是一个好的代码。

如何从 ListAdapter 中获取 LifecycleOwner

class VoiceAdapters (private val aHomeViewModel: HomeViewModel, private val mPlay: PlayInterface):
        ListAdapter<MVoice, VoiceAdapters.VoiceViewHolder>(MVoiceDiffCallback()) {

    private lateinit var mContext: Context
    private lateinit var mLifecycleOwner:LifecycleOwner

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
        mContext = parent.context
        mLifecycleOwner = mContext as LifecycleOwner

        return VoiceViewHolder(
            LayoutVoiceItemBinding.inflate(LayoutInflater.from(parent.context), parent, false).also {               
               it.lifecycleOwner = mLifecycleOwner
               it.aHomeViewModel = aHomeViewModel
            }
        )
    }

    ...
}
2个回答

8
  1. 将其作为构造函数参数传递给VoiceAdapters
  2. 创建扩展属性:
   val View.lifecycleOwner get() = ViewTreeLifecycleOwner.get(this)`

然后访问它:parent.lifecycleOwner

  1. 仅解析一次:

 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
       if(!::lifecycleOwner.isInitialized){
        lifecycleOwner = parent.context as LifecycleOwner
      }
}

它们指向相同的 LifecycleOwner,即用于填充布局的Context

ViewTreeLifecycleOwner.get(view)是获取视图底层的LifecycleOwner的一种便捷方式。 因此,我认为选项1或2更好。


这个并没有按照预期工作,并且在设置时显示错误。 - Rishabh Deep Singh
这个问题在于内存泄漏! - Gilberto Ibarra

-1
如果您通过构造函数传递上下文参数到适配器中,那么您可以使用点运算符.获取所有与该活动相关的参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接