0

I am trying to add View Binding in my RecyclerView's adapter like this:-

class MyAdapter(private val myList: List<MyData>) : RecyclerView.Adapter<MyViewHolder>()
{
    private var _binding: MyItemBinding? = null
    private val binding get() = _binding!!

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder
    {
        _binding = MyItemBinding.inflate(LayoutInflater.from(parent.context))
        return MyViewHolder(
                binding.root)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int)
    {
        val itemData = myList[position]
        binding.myItemImage.setImageResource(itemData.myImage)
    }

    override fun getItemCount(): Int = myList.size
}

class MyViewHolder(internal var containerView: View) : RecyclerView.ViewHolder(containerView)

To avoid any memory leaks, we should call destory the binding by setting

_binding = null

But I am not able to find the callback corresponding to onCreateViewHolder() where I can do that. There is no callback like onDestroyViewHolder() in the lifecycle of RecyclerView.Adapter.

I need help in understanding where should I destroy the binding?

Rohit Singla
  • 112
  • 2
  • 9
  • Adapter should not hold any binding + you are storing binding only of the lastly created view holder. `ViewHolder` is the UI part of the adapter. You can use ViewBinding to `.inflate` it and then use `.bind `in `onBindViewHolder` – TheLibrarian Oct 18 '22 at 08:40
  • @TheLibrarian Thanks for your response. Can you please provide a good reference (like working example) for this? I am bit confused. – Rohit Singla Oct 18 '22 at 08:47
  • See [here](https://developer.android.com/develop/ui/views/layout/recyclerview#implement-adapter) how to correctly implement Adapter with Viewholders. And no, you don't need to destroy or free any bindings within the viewholder. You just (re)bind data to it. The rest is handled for you. – Till - Appviewer.io Oct 18 '22 at 10:52

0 Answers0