clicklistener 在 recyclerview 中不起作用

Posted

技术标签:

【中文标题】clicklistener 在 recyclerview 中不起作用【英文标题】:clicklistener not working in recyclerview 【发布时间】:2021-02-08 09:38:03 【问题描述】:

我正在关注此链接答案--> https://***.com/a/32323801/12553303 ...单击项目时,我收到无效产品ID的错误...但是我如何从适配器获取ID到活动???????我已经使用了点击监听器的界面...... 在这里需要帮助 --> RetrofitClient.instance.deletecart(token, dataList?.get(position)?.product_id.toString())

关于调试这条线

以下是我的代码:--

class CartAdapter(private val context: Context, private val dataList: MutableList<DataCart?>?) :
RecyclerSwipeAdapter<CartAdapter.CustomViewHolder>() , AdapterView.OnItemSelectedListener //added RecyclerSwipeAdapter and override

var progressDialog: ProgressDialog? = null

private var itemClick: OnItemClick? = null

inner class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    val mView: View
  val swipelayout:SwipeLayout
    val productiamge: ImageView
    val productname: TextView
    val productcategory: TextView
    val productprice: TextView
    val tvDelete:TextView
    val spin:Spinner
    init 
        mView = itemView
    productiamge= mView.findViewById(R.id.imagecart)
       productname= mView.findViewById(R.id.imagenamecart)
        productcategory= mView.findViewById(R.id.imagecategory)

     productprice =mView.findViewById(R.id.price)
        swipelayout=mView.findViewById(R.id.swipe)
        tvDelete=mView.findViewById(R.id.tvDelete)
         spin = mView.findViewById(R.id.spinner) as Spinner
        tvDelete.setClickable(true);
        tvDelete.setOnClickListener 
            if (itemClick != null) 
                itemClick!!.onItemClicked(getPosition());
            
        


    




override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder 
    val layoutInflater = LayoutInflater.from(parent.context)
    val view: View = layoutInflater.inflate(R.layout.addtocart_item, parent, false)

    return CustomViewHolder(view)


override fun getSwipeLayoutResourceId(position: Int): Int 
    return R.id.swipe;



override fun onBindViewHolder(holder: CustomViewHolder, position: Int) 
  val  progressDialog :ProgressDialog= ProgressDialog(context);
    holder.productname.text = dataList?.get(position)?.product?.name ?: null
    holder.productcategory.text = "(" +dataList?.get(position)?.product?.product_category +")"

    holder.productprice.text = dataList?.get(position)?.product?.cost.toString()

    Glide.with(context).load(dataList?.get(position)?.product?.product_images)
        .into(holder.productiamge)

    holder.swipelayout.setShowMode(SwipeLayout.ShowMode.PullOut)
    Log.e("checkidd", dataList?.get(position)?.product?.id.toString())
    // Drag From Right

    // Drag From Right
    holder.swipelayout.addDrag(
        SwipeLayout.DragEdge.Right,
        holder.swipelayout.findViewById(R.id.bottom_wrapper)
    )



    //im not able to get this id in activity
     val id =dataList?.get(position)?.product?.id

    holder.swipelayout.addSwipeListener(object : SwipeListener 
        override fun onClose(layout: SwipeLayout) 
            //when the SurfaceView totally cover the BottomView.
        

        override fun onUpdate(layout: SwipeLayout, leftOffset: Int, topOffset: Int) 
            //you are swiping.
        

        override fun onStartOpen(layout: SwipeLayout) 
        override fun onOpen(layout: SwipeLayout) 
        

        override fun onStartClose(layout: SwipeLayout) 
        override fun onHandRelease(
            layout: SwipeLayout,
            xvel: Float,
            yvel: Float
        ) 
        
    )


    holder.swipelayout.getSurfaceView()
        .setOnClickListener(View.OnClickListener 
        )


    holder.tvDelete.setOnClickListener(View.OnClickListener  view ->
        mItemManger.removeShownLayouts(holder.swipelayout)
        notifyItemChanged(position)
        notifyItemRemoved(position)
        dataList?.removeAt(position)
        notifyItemRangeChanged(position, dataList?.size!!)
        mItemManger.closeAllItems()
                itemClick?.onItemClicked(position)

    )
    mItemManger.bindView(holder.itemView, position)



    override fun getItemCount() = dataList?.size ?: 0

fun progress()

    progressDialog?.dismiss()
    val intent =
        Intent(context.applicationContext, AddToCart::class.java)
    intent.flags =
        Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
    context.applicationContext.startActivity(intent)
    (context as Activity?)!!.overridePendingTransition(0, 0)







override fun onNothingSelected(p0: AdapterView<*>?) 
    TODO("Not yet implemented")


override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) 



fun getItemClick(): OnItemClick? 
    return itemClick


fun setItemClick(itemClick: OnItemClick?) 
    this.itemClick = itemClick

活动:---------

    class AddToCart:BaseClassActivity(), OnItemClick
   val dataList: MutableList<DataCart?>? = null

override fun onCreate(savedInstanceState: Bundle?) 
    super.onCreate(savedInstanceState)
    setContentView(R.layout.add_to_cart)
    getWindow().setExitTransition(null)
    getWindow().setEnterTransition(null)
    var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
    setSupportActionBar(mActionBarToolbar);
    // add back arrow to toolbar
  setEnabledTitle()

    mActionBarToolbar.setNavigationOnClickListener(View.OnClickListener 
        onBackPressed()
    )
    placeorder.setOnClickListener 
        val intent:Intent=Intent(applicationContext, AddressActivity::class.java)
        startActivity(intent)
    
      loadCart()


  fun loadCart()

  val model = ViewModelProvider(this)[CartViewModel::class.java]

  model.CartList?.observe(this, object : Observer<CartResponse> 
      override fun onChanged(t: CartResponse?) 

          generateDataList(t?.data?.toMutableList())
          totalamount.setText(t?.total.toString())
      
  )
  

fun generateDataList(dataList: MutableList<DataCart?>?) 
    val recyclerView=findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
    val linear:LinearLayoutManager=
        LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
    recyclerView?.layoutManager=linear
    val adapter = CartAdapter(this@AddToCart, dataList)
    recyclerView?.adapter=adapter
    recyclerView?.addItemDecoration(DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
   // recyclerView?.setHasFixedSize(true)
    adapter.setItemClick(this);

    adapter.notifyDataSetChanged()
    if (dataList?.isEmpty() ?: true) 
        recyclerView?.setVisibility(View.GONE)
        totalamount.setVisibility(View.GONE)
        fl_footer.setVisibility(View.GONE)
        placeorder.setVisibility(View.GONE)
        emptytext.setVisibility(View.VISIBLE)
     else 
        recyclerView?.setVisibility(View.VISIBLE)
        totalamount.setVisibility(View.VISIBLE)
        fl_footer.setVisibility(View.VISIBLE)
        placeorder.setVisibility(View.VISIBLE)
        emptytext.setVisibility(View.GONE)


    
  recyclerView?.addOnScrollListener(object :
      RecyclerView.OnScrollListener() 
      override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) 
          super.onScrollStateChanged(recyclerView, newState)
          Log.e("RecyclerView", "onScrollStateChanged")
      

      override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) 
          super.onScrolled(recyclerView, dx, dy)
      
  )

override fun onBackPressed() 
    super.onBackPressed()
    val intent = Intent(this, HomeActivity::class.java)
 startActivity(intent)

override fun onOptionsItemSelected(item: MenuItem): Boolean 
    return when (item.itemId) 
        android.R.id.home -> 
            NavUtils.navigateUpFromSameTask(this)

            true
        
        else -> super.onOptionsItemSelected(item)
    


override fun onResume() 
    super.onResume()
 loadCart()



override fun onItemClicked(position: Int) 

    val token: String = SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
    RetrofitClient.instance.deletecart(token, dataList?.get(position)?.product_id.toString())
        .enqueue(object : Callback<DeleteResponse> 
            override fun onFailure(call: Call<DeleteResponse>, t: Throwable) 

                Log.d("res", "" + t)


            

            override fun onResponse(
                call: Call<DeleteResponse>,
                response: Response<DeleteResponse>
            ) 
                var res = response

                if (res.body()?.status == 200) 
                    Toast.makeText(
                        applicationContext,
                        res.body()?.message,
                        Toast.LENGTH_LONG
                    ).show()



                 else 
                    try 
                        val jObjError =
                            JSONObject(response.errorBody()!!.string())
                        Toast.makeText(
                            applicationContext,
                            jObjError.getString("message") + jObjError.getString("user_msg"),
                            Toast.LENGTH_LONG
                        ).show()
                     catch (e: Exception) 
                        Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
                        Log.e("errorrr", e.message)
                    
                
            
        )

需要帮助,谢谢

【问题讨论】:

我不清楚你的问题 你能在适配器val id =dataList?.get(position)?.product?.id中看到这条语句吗? 如何在活动中获得它? 你知道如何实现接口模式或回调模式吗? 这是我第一次...@JeelVankhede 我还在尝试 【参考方案1】:

要将响应/数据从适配器返回到活动,您需要实现如下示例的回调模式:

RecyclerView 适配器 sudo 代码:

class RecyclerViewAdapter(
    other variables,
    private val dataCallback: (Desired data type you want to return to activity) -> Unit // This is how you can construct lambda callback in Kotlin
): RecyclerView.Adaper..()
    
    override fun onBindViewHolder(...) 
        // Let's say here you have click listener or some other event on which you want data to send back to activity then simply call like below:
        dataCallback(outputData) // This can be `dataList?.get(position)?.product?.id`
    

活动回调 sudo 代码:

class SampleActivity: AppCompatActivity() 
    lateinit var adapter: RecyclerViewAdapter

    override fun onCreate(...)
        adapter = RecyclerViewAdapter(other values)  desiredData ->
            // Here you can receive data back as callback
        

        // Example from O.P.
        // val adapter = CartAdapter(this@AddToCart, dataList)  output ->  
    

基本上,您在适配器构造函数上创建回调接收器类型,如下所示:

nameOfCallbackVariable: (TypeOfDataYouWantToProvideBack) -&gt; ReturnType

productSelectedCallback: (Int) -&gt; Unit 将您选择的 id (Int) 发回给消费者。

当您需要返回该数据时,您可以像这样调用它:nameOfCallbackVariable(valueOfIntType)

【讨论】:

嘿,微调器需要帮助 --> ***.com/questions/64537639/… 在我看来,您提供的细节比提供整个代码所需的要多得多。您应该考虑将范围限制为实际问题并详细解释。因为我试图调查但无法找出代码中的实际问题。 从视图模型实现看 我在不使用 viewmodel 的情况下得到了正确的解决方案,但是当我使用 viewmodel 时,我无法获得正确的输出 这就是为什么我把这两种方法都放在了,这样你就可以了解发生了什么

以上是关于clicklistener 在 recyclerview 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Android、Layout clicklistener 和 subview 点击问题

如何在 RecyclerView 适配器中的 ClickListener 上显示 AlertDialog

Android按钮视图绑定ClickListener不起作用

自定义按钮的 ClickListener

添加 ClickListener JQuery Mobile ListView

添加ClickListener JQuery Mobile ListView