Issue
At present, I use mLifecycleOwner = mContext as LifecycleOwner
to get LifecycleOwner
, it can work, but I don't think it's a good code.
How can I get LifecycleOwner
from ListAdapter
?
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
}
)
}
...
}
Solution
- Pass it as constructor param in the
VoiceAdapters
- Create extension property:
val View.lifecycleOwner get() = ViewTreeLifecycleOwner.get(this)`
then access it: parent.lifecycleOwner
- Resolve it only once:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
if(!::lifecycleOwner.isInitialized){
lifecycleOwner = parent.context as LifecycleOwner
}
}
They are pointing to the same LifecycleOwner
, the Context
that was used to inflate the layout.
ViewTreeLifecycleOwner.get(view)
is convenient way to obtain the view's underlying LifecycleOwner
. Therefore, my two cents go to option 1 or 2.
Answered By - Nikola Despotoski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.