I have a function which returns an object of `View...
# announcements
c
I have a function which returns an object of
ViewHolder
Copy code
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    return when (viewType) {
        0 -> ViewHolder(CategoryHeaderBinding.inflate(LayoutInflater.from(parent.context), parent,false))


        else -> ViewHolder(CategoryCardBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }
}
it passes either
CategoryHeaderBinding
or
CategoryCardBinding
to
ViewHolder
Copy code
class ViewHolder(private val binding: CategoryCardBinding OR CategoryHeaderBinding) :
        RecyclerView.ViewHolder(binding.root) {
    }
How do I make
ViewHolder
accepts
binding
to be either
CategoryCardBinding
or
CategoryHeaderBinding
c
I think you'll need to either have two functions, for each of the types or to have some kind of class containing one of those two types. Or you could also add a common interface for those two classes
c
Does it matter if onCreateViewHolder expecting a ViewHolder return type?
r
What are you doing with the
binding
? Are you just setting variables in
binding
?
c
the binding is for
Copy code
fun bind(subcategory: Subcategory) {
    binding.subcategory = subcategory
}

fun bind(brand: Brand) {
    binding.brand = brand
}
basically
binding
allows me to update something
the
bind
function is inside
ViewHolder
r
then you can do this:
Copy code
class MyViewHolder(private val binding: ViewDataBinding): RecyclerView.ViewHolder(binding.root) {
    fun bind(subcategory: Subcategory) {
        binding.setVariable(BR.subcategory, subcategory)
        binding.executePendingBindings()
    }

    fun bind(brand: Brand) {
        binding.setVariable(BR.brand, brand)
        binding.executePendingBindings()
    }
}
ViewDataBinding.setVariable
will set variable if it exists in the layout. •
BR
here is
<your.package.name>.BR
c
Thank you very much 💯