android kotlin -how to add click listener to Recyc

2019-09-22 01:31发布

问题:

I'm new in kotlin ,this is my adapter code , it works find and I've no problem , now ,I need to implement click listener for it , here is my code :

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)
}
}

I want to add click listener, I used to do it in viewholder class where I implement click listener

how can I do it in kotlin , ? i've tied so many ways but no success

回答1:

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)
    }
}

and in your activity just implement click listener

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

   }
})