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

How can I get LifecycleOwner reference in RecyclerView.Adapter?

目前我用mLifecycleOwner = 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
            }
        )
    }

    ...
}
  1. VoiceAdapters
  2. 中将其作为构造函数参数传递
  3. 创建扩展 属性:
   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。

如果您通过构造函数在适配器中传递 context,您可以使用 . 运算符获取与该 activity 相关的所有参数。