kotlin BaseAdapter封装

1.新建 BaseRecyclerViewAdapter 类

 

abstract class BaseRecyclerViewAdapter(var mContext: Context) : RecyclerView.Adapter() {

    //ItemClick事件
    var mItemClickListener: OnItemClickListener? = null

    var mItemLongClickListener: OnItemLongClickListener? = null

    //数据集合
    var dataList: MutableList = mutableListOf()
    /*
        设置数据
        Presenter处理过为null的情况,所以为不会为Null
     */
    fun setData(sources: MutableList) {
        dataList = sources
        notifyDataSetChanged()
    }

    fun addAll(sources: MutableList) {
        dataList.addAll(sources)
        notifyDataSetChanged()
    }

    fun clear() {
        dataList.clear()
        notifyDataSetChanged()
    }
    fun notifyDataSetChang() {
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: VH, position: Int) {

        holder.itemView.setOnClickListener {
            if (mItemClickListener != null)
                mItemClickListener!!.onItemClick(dataList[position], position)
        }

    }

    override fun getItemCount(): Int {
        return dataList.size
    }
    /*
        ItemClick事件声明
     */
    interface OnItemClickListener {
        fun onItemClick(item: T, position: Int)
    }

    interface OnItemLongClickListener {
        fun onItemLongClick(item: T, position: Int)
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.mItemClickListener = listener
    }

    fun setOnItemLongClickListener(listener: OnItemLongClickListener) {
        this.mItemLongClickListener = listener
    }

}

使用 :


class BeadhousePopWindowAdapter(context: Context) : BaseRecyclerViewAdapter(context) {
    var id = 0
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.beadhouse_pop_adapter, null, false))

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        
        holder.itemView.checked.text = dataList[position]
        //接口回调
        holder.itemView.checked.setOnClickListener({
            id = position
            mItemClickListener!!.onItemClick(dataList.get(position),position)
        })
    }
    class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view)
}
/*  = object : 你的Adapter.接口回调名字*/
        beadhousePopWindowAdapter.mItemClickListener = object : BaseRecyclerViewAdapter.OnItemClickListener {
            override fun onItemClick(item: String, position: Int) {
             beadhousePopWindowAdapter.notifyDataSetChanged()
                beadhousePopWindow2Adapter.setData(mutableList2[position].list)
            }
        }

 

你可能感兴趣的:(kotlin BaseAdapter封装)