RecyclerView添加ItemClickListener

2020-04-21  本文已影响0人  Leero丶
1、声明OnItemClickListener
interface OnItemClickListener<T> {
        fun onItemClick(view: View, position: Int, data: T)
}
2、设置OnItemClickListener
private var mItemClickListener: OnItemClickListener<ChannelEntity>? = null

fun setItemClickListener(listener: OnItemClickListener<ChannelEntity>) {
    this.mItemClickListener = listener
}
3、引用OnItemClickListener
override fun onBindViewHolder(holder: ChannelViewHolder, position: Int) {
    ......
    holder.itemView.setOnClickListener {
        mItemClickListener?.onItemClick(it, position, channel)
    }
}
完整示例
class ChannelAdapter(channels: List<ChannelEntity>) :
    RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder>() {

    companion object {
        private const val TYPE_NORMAL = 1
        private const val TYPE_MEDIUM = 2
        private const val TYPE_MULTIPLE = 3
    }

    interface OnItemClickListener<T> {
        fun onItemClick(view: View, position: Int, data: T)
    }

    inner class ChannelViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val channelName: TextView = itemView.findViewById(R.id.tv_channel)
        val channelIcon: ImageView = itemView.findViewById(R.id.iv_icon)
    }

    private var mChannelList: List<ChannelEntity> = channels
    private var mItemClickListener: OnItemClickListener<ChannelEntity>? = null

    fun setItemClickListener(listener: OnItemClickListener<ChannelEntity>) {
        this.mItemClickListener = listener
    }

    override fun getItemViewType(position: Int): Int {
        return when (mChannelList.size) {
            2 -> {
                TYPE_NORMAL
            }
            3 -> {
                TYPE_MEDIUM
            }
            else -> {
                TYPE_MULTIPLE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChannelViewHolder {
        val view: View = when (viewType) {
            TYPE_NORMAL -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_home_channel_normal, parent, false)
            }
            TYPE_MEDIUM -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_home_channel_medium, parent, false)
            }
            else -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_home_channel_multiple, parent, false)
            }
        }
        return ChannelViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: ChannelViewHolder, position: Int) {
        val channel = mChannelList[position]
        holder.channelIcon.setImageResource(channel.icon)
        holder.channelName.text = channel.name

        holder.itemView.setOnClickListener {
            mItemClickListener?.onItemClick(it, position, channel)
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读