'How to create BaseAdapter for RecyclerView with ViewBinding?

I want to create a BaseAdapter class for RecyclerView with ViewBinding, but when I tried the following code:

    class SimpleListAdapter<T, K: ViewBinding>(
        private val itemBinding: K,
        val bindFun:(viewBinding:K, listType:T)->Unit
    ): RecyclerView.Adapter<SimpleListAdapter.ViewHolder<K>>() {


        var list:List<T> = emptyList()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<K> {
            return ViewHolder(itemBinding)
        }

        override fun getItemCount()= list.size


        override fun onBindViewHolder(holder: ViewHolder<K>, position: Int) {
            val listItem=list[position]
            bindFun(holder.binding,listItem)
        }

        class ViewHolder<K:ViewBinding>(val binding: K): RecyclerView.ViewHolder(binding.root)
    }

    class HabitListFragment : Fragment() {

        private  val viewModel: HabitListViewModel by lazy{
            ViewModelProvider(this).get(HabitListViewModel::class.java)
        }

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View {
            val itemBinding=HabitListItemBinding.inflate(inflater)

            val listAdapter=SimpleListAdapter<SummaryTumple,HabitListItemBinding>(itemBinding){
                    habitListItemBinding: HabitListItemBinding, summaryTumple: SummaryTumple ->
                        habitListItemBinding.desc.text=summaryTumple.description
                        habitListItemBinding.title.text=summaryTumple.title
            }

        /*....*/

        }

    }

I got an error:

java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot) at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6796)

I'm confused, and cannot figure out the cause. How should I solve it?



Solution 1:[1]

You didn't attach your XML, but I had a similar problem which arose from not having android:id="@+id/root" on the root element of the layout. So, when I referenced binding.root, it returned a view with a parent, which caused the exception.

Solution 2:[2]

Make sure you have imported the correct ViewBinding class

import androidx.viewbinding.ViewBinding

If you get an error then upgrade your Gradle version to minimum 7.0.0 classpath 'com.android.tools.build:gradle:7.0.0'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tad
Solution 2 Bharat Lalwani