• ListAdapter不需要得到size。因为传入多少数据,它的size默认就是多大。一共需要传入三个类型,一个数据类型,一个ViewHolder,最后一个就是构造函数中的Diffutil,用来局部更新RecyclerView,不需要考虑乱序等问题,也不需要notifichanged,不会影像RecyclerView的性能
    1. // 写一个构造用来给item设置点击事件回调
    2. class LocationAdapter(private val itemClick: (String) -> Unit) :
    3. ListAdapter<String, LocationAdapter.ViewHolder>(
    4. object : DiffUtil.ItemCallback<String>() {
    5. override fun areItemsTheSame(
    6. oldItem: String,
    7. newItem: String
    8. ) =
    9. oldItem == newItem
    10. override fun areContentsTheSame(
    11. oldItem: String,
    12. newItem: String
    13. ) =
    14. oldItem == newItem
    15. }
    16. ) {
    17. inner class ViewHolder(view: LocationItemBinding) : RecyclerView.ViewHolder(view.root) {
    18. private val title = view.companyName
    19. val root = view.root
    20. fun bind(string: String) {
    21. title.text = string.name_en
    22. }
    23. }
    24. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
    25. LocationItemBinding.inflate(
    26. LayoutInflater.from(parent.context),
    27. parent,
    28. false
    29. )
    30. ).apply {
    31. root.setOnClickListener {
    32. itemClick(getItem(absoluteAdapterPosition)) // getItem(index)函数可以拿到Rv中的某一项
    33. }
    34. }
    35. override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    36. holder.bind(getItem(position))
    37. }
    38. }
    • 在View中使用 ```kotlin // 大括号为item点击事件 private val locationAdapter = LocationAdapter {
      1. binding.loginBox.spinner.setText(it.name_en)
      2. binding.loginBox.locationRecyclerview.isVisible = false
      3. locationId = it.location_id
      }

    locationRecyclerview.apply { layoutManager = GridLayoutManager(requireContext(), 1) adapter = locationAdapter } locationAdapter.submitList(data) // 提交数据 locationAdapter.submitList(data){ // 数据填充完成后的回调 参数多选

    } ```