我想在recyclerview项目上实现onClickListener。这是我的CustomAdapter.kt代码。

package com.png.kotlinsample

/**
 * Created by admin on 13-08-2017.
 */
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView

/**
 * Created by prashant on 6/19/2017.
 */

class CustomAdapter(val userList: ArrayList<User>, val listener: (User) -> Unit) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    //this method is returning the view for each item in the list
        class MyAdapter(val userList: ArrayList<User>)
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position],listener)
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return userList.size
    }

    //the class is hodling the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(user: User, listener: (User) -> Unit) = with(itemView) {
            val textViewName = itemView.findViewById(R.id.textViewUsername) as TextView
            val textViewAddress  = itemView.findViewById(R.id.textViewAddress) as TextView
            textViewName.text = user.name
            textViewAddress.text = user.address
            setOnClickListener { listener(user) }
        }




    }
}

我想从我的 Activity 中获取点击监听器回调。

最佳答案

class CustomAdapter(
    val userList: List<User>,
    val listener: (User) -> Unit
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder = ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false))

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position])
    }

    override fun getItemCount(): Int = userList.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val textViewName: TextView = itemView.findViewById(R.id.textViewUsername)
            private val textViewAddress: TextView  = itemView.findViewById(R.id.textViewAddress)

        fun bindItems(user: User) = with(itemView) {
            textViewName.text = user.name
            textViewAddress.text = user.address
            setOnClickListener { listener(user) }
        }
    }
}

然后
val adapter = CustomAdapter(userList) { user ->
    // do something with user on click
}
recyclerView.adapter = adapter

07-28 02:19