RecyclerView itemClick 在 kotlin android 中不起作用

问题描述 投票:0回答:0

我正在尝试在 rv 列表上执行 onClickListener,但它不起作用,我可以知道我错过了什么吗?就像我尝试过其他方法一样它也不起作用,就像我也尝试过这种方式https://www.youtube.com/watch?v=bcrI2V6cUvM&ab_channel=WLPROJECT

下面是代码: 片段:

class ListOfProductsFragment : BaseFragment(), ListOfProductsView, ProductOnClickListener {

 private fun setUpRecyclerView() {
    productsAdapter = ListOfProductsAdapter(requireContext(), price, isOfferAvail)
    productsAdapter.setClickListener(this)
    binding.rvListOfProducts.apply {
      layoutManager = LinearLayoutManager(requireContext())
      setHasFixedSize(true)
      adapter = productsAdapter
      scrollToPosition(0)
    }
  }

  override fun onItemClick(model: Product) {
    startActivity(ProductDetailActivity.getCallingIntent(context(), model.pid))
  }
}

下面是adapter和onClickListener接口


class ListOfProductsAdapter(
  private val context: Context,
  private val price: String?,
  private val isOfferAvail: Boolean?
) : Adapter<ListOfProductViewHolder>() {
  private val layoutInflater: LayoutInflater = LayoutInflater.from(context)
  private val productModelList = mutableListOf<Product>()
  private var clickListener: ProductOnClickListener? = null

  fun setClickListener(
    clickListener: ListOfProductsFragment
  ) {
    this.clickListener = clickListener
  }


  override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
  ): ListOfProductViewHolder {
    return ListOfProductViewHolder(ItemHomeProductBigSizeBinding.inflate(layoutInflater, parent, false))
  }

  override fun getItemCount(): Int {
    return productModelList.size
  }

  override fun onBindViewHolder(
    holder: ListOfProductViewHolder,
    position: Int
  ) {
    val productUiModel = productModelList[position]
      holder.binding.root.setOnClickListener {
        clickListener?.onItemClick(productModelList[holder.bindingAdapterPosition])
      }
    }
  }

  fun setProductUiModels(viewModels: List<Product>?) {
    productModelList.clear()
    productModelList.addAll(viewModels!!)
    notifyDataSetChanged()
  }

  interface ProductOnClickListener {
    fun onItemClick(model: Product)
  }

  inner class ListOfProductViewHolder(val binding: ItemHomeProductBigSizeBinding) : ViewHolder(binding.root){
    init {
      binding.root.setOnClickListener {
        clickListener?.onItemClick(productModelList[bindingAdapterPosition])
      }
    }
  }
}

是的,我试过上面的代码,但 ItemClick 不工作,请建议我错过了什么

kotlin android-recyclerview onitemclick
© www.soinside.com 2019 - 2024. All rights reserved.