我想使用 ViewBinding 为 RecyclerView 创建一个 BaseAdapter 类,但是当我尝试以下代码时:
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
}
/*....*/
}
}
我收到一个错误:
java.lang.IllegalStateException:创建时不得附加 ViewHolder 视图。确保您没有将“true”传递给 androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6796) 的 LayoutInflater.inflate(..., boolean attachToRoot) 的 attachToRoot 参数
我很困惑,无法找出原因。我该如何解决?