android kotlin-如何将单击侦听器添加到RecyclerView适配器

时间:2019-01-16 15:00:01

标签: android kotlin android-recyclerview

我是kotlin的新手,这是我的适配器代码,可以正常工作,并且我没有问题,现在,我需要为其实现点击侦听器,这是我的代码:

class CategoryAdapter(val context: Context,val list: List<CategoryItems>): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {
var typeface: Typeface? = Func.getTypeFace(context)

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    var catRow=list.get(position)

    holder?.tvTitle.text = catRow.name
    holder?.tvTitle.setTypeface(typeface)
    Glide.with(context).load(Const.BaseUrl+"Opitures/"+  catRow.icon_name).into(holder?.imgCat);
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val v = LayoutInflater.from(parent?.context).inflate(R.layout.category_item, parent, false)
    return ViewHolder(v);
}

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

class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
    val tvTitle = itemView.findViewById<TextView>(R.id.tv_cat_title)
    val imgCat = itemView.findViewById<ImageView>(R.id.img_cat)
}
}

我想添加点击侦听器,我曾经在实现点击侦听器的viewholder类中这样做

我如何在Kotlin中做到这一点?我有很多方法,但没有成功

1 个答案:

答案 0 :(得分:4)

lateinit var mClickListener: ClickListener

fun setOnItemClickListener(aClickListener: ClickListener) {
    mClickListener = aClickListener
}

interface ClickListener {
    fun onClick(pos: Int, aView: View)
}

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
    override fun onClick(v: View) {
        mClickListener.onClick(adapterPosition, v)
    }
    val tvTitle = itemView.findViewById<TextView>(R.id.tv_cat_title)

    init {
        itemView.setOnClickListener(this)
    }
}

在您的活动中只需实现点击侦听器

adapter.setOnItemClickListener(object : Adapter.ClickListener {
                            override fun onClick(pos: Int, aView: View) {

   }
})