I'm trying to convert one of my former "kotlin-android-extensions" activities to View Binding. Every example I've seen of this seems to contain some variant of the line:
binding = MyActivityBiding.inflate(layoutInflater)
Yet when I attempt to use layoutInflater I get the error:
Unresolved reference: layoutInflater
I understand it appears to be a variable from Layoutinflater... but no one ever seems to need to define it in any of the examples I've found. And when I attempt to define "layoutInflater" myself using LayoutInflater... I can never get the context from anywhere.
Anyway... here is my code:
open class ExpandableCommentIndie constructor(
private val comment : Comment,
private val depth : Int) : Item<GroupieViewHolder>(), ExpandableItem {
private lateinit var expandableGroup: ExpandableGroup
private lateinit var binding: ItemEcBinding
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
addingDepthViews(viewHolder)
binding = ItemEcBinding.inflate(layoutInflater)
binding.tvUser.setText(comment.speaker.toString())
}
All you need to get a LayoutInflater
is a Context
which is somehow related to a UI component. So Activity
(which is a kind of Context
), Fragment.context
and View.context
will do.
Since GroupieViewHolder extends RecyclerView.ViewHolder
, it has a property itemView: View
. So you can get the LayoutInflater
as follows:
val layoutInflater = LayoutInflater.from(viewHolder.itemView.context)
The whole function:
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
addingDepthViews(viewHolder)
val layoutInflater = LayoutInflater.from(viewHolder.itemView.context)
binding = ItemEcBinding.inflate(layoutInflater)
binding.tvUser.setText(comment.speaker.toString())
}