android kotlin button in recyclerview item click code example

Example 1: how to set onClickListener to RecyclerView kotlin

/* 
How to set up a click listener on RecyclerView in conjunction with
an adapter and a click listener on items
NOT only *RecyclerView itemClickListener*
*RecyclerView onClickListener* and *RecyclerView itemClickListener* together
often such a solution is needed to close pop-up messages 
when clicking anywhere on the screen with RecyclerView list 
This code is more like a crutch but works great for me
*/
private fun CreateRecyclerView(){
   val recycler_list = findViewBiId<RecyclerView>(R.id.myRecyclerViewId)

   recycler_list.setOnTouchListener { v, _ ->
      // if statement is return boolean value for OnTouchListener
      if (layoutAttachment.visibility == View.VISIBLE || menuButtons.visibility == View.VISIBLE) {
        closeOpenDialogs()
        v.performClick()
      } else {
        false
      }
   } 
  recycler_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
  recycler_list.setHasFixedSize(true)
  recycler_list.adapter = myAdapter
  recycler_list.itemAnimator = DefaultItemAnimator()
}

private fun closeOpenDialogs(){
// here do staff for you need click actions like
  if (layoutAttachment.visibility == View.VISIBLE || menuButtons.visibility == View.VISIBLE) {
    layoutAttachment.visibility == View.GONE
    menuButtons.visibility == View.GONE
  }
}

Example 2: button inside a recycle view in android in kotlin

val myButton = itemView.findViewById<Button>(R.id.myButton) // This is your Button, you declared in your xml file.
    val fCard = itemView.findViewById<CardView>(R.id.cardOnFront)
    val packetTime = itemView.findViewById<TextView>(R.id.timeofPacket)
    val timeMessage = itemView.findViewById<TextView>(R.id.messageofTime)
    val bCars = itemView.findViewById<CardView>(R.id.backCard)
    val drugs = itemView.findViewById<TextView>(R.id.drugs)
    val note = itemView.findViewById<TextView>(R.id.note)
    val dosage = itemView.findViewById<TextView>(R.id.dosage)

Tags:

Misc Example